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 4, 2024
1 parent 02fa714 commit 27bfff3
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions astroid/nodes/node_ng.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
overload,
)

from astroid import util
from astroid import nodes, util
from astroid.context import InferenceContext
from astroid.exceptions import (
AstroidError,
Expand Down 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 27bfff3

Please sign in to comment.