Skip to content

Commit bf7713e

Browse files
committed
be honest that non-Module root is possible; return None in such cases
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.
1 parent b76ad19 commit bf7713e

File tree

1 file changed

+5
-4
lines changed

1 file changed

+5
-4
lines changed

astroid/nodes/node_ng.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -326,17 +326,18 @@ def scope(self) -> nodes.LocalsDictNodeNG:
326326
raise ParentMissingError(target=self)
327327
return self.parent.scope()
328328

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

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

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

0 commit comments

Comments
 (0)