Skip to content

Commit

Permalink
be honest that non-Module root is possible; return None in such cases
Browse files Browse the repository at this point in the history
The nodes are often created in an ad-hoc way, and their parent is not
   always set. We can't control for that invariant in the constructor,
   since the parent is usually set outside of the constructor. So,
   let's just be honest that we might not have Module as the root.
  • Loading branch information
temyurchenko committed Sep 3, 2024
1 parent b76ad19 commit bf7713e
Showing 1 changed file with 5 additions and 4 deletions.
9 changes: 5 additions & 4 deletions astroid/nodes/node_ng.py
Original file line number Diff line number Diff line change
Expand Up @@ -326,17 +326,18 @@ def scope(self) -> nodes.LocalsDictNodeNG:
raise ParentMissingError(target=self)
return self.parent.scope()

def root(self) -> nodes.Module:
def root(self) -> nodes.Module | None:
"""Return the root node of the syntax tree.
:returns: The root node.
:returns: The root node. Might be None, if the node has been
created ad-hoc, e.g. with nodes.const_factory
"""
if not (parent := self.parent):
return self # type: ignore[return-value] # Only 'Module' does not have a parent node.
return self if isinstance(self, nodes.Module) else None

while parent.parent:
parent = parent.parent
return parent # type: ignore[return-value] # Only 'Module' does not have a parent node.
return parent if isinstance(parent, nodes.Module) else None

def child_sequence(self, child):
"""Search for the sequence that contains this child.
Expand Down

0 comments on commit bf7713e

Please sign in to comment.