diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py index 3a482f3cc..5ef347df5 100644 --- a/astroid/nodes/node_ng.py +++ b/astroid/nodes/node_ng.py @@ -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.