From f38ffc1e7e478c5e184d161b9e55ce8a11f02299 Mon Sep 17 00:00:00 2001 From: Artem Yurchenko Date: Tue, 3 Sep 2024 16:19:42 -0700 Subject: [PATCH] assert that the root() is always a Module The nodes are often created in an ad-hoc way, and their parent is not always set. We can't control for that invariant fully in the constructor, since the parent is sometimes set outside of the constructor. The previous commits did their best to clean up such situations, but let's add an assert just in case. --- astroid/nodes/node_ng.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/astroid/nodes/node_ng.py b/astroid/nodes/node_ng.py index 6d149e384..afbeef709 100644 --- a/astroid/nodes/node_ng.py +++ b/astroid/nodes/node_ng.py @@ -21,7 +21,7 @@ overload, ) -from astroid import util +from astroid import nodes, util from astroid.context import InferenceContext from astroid.exceptions import ( AstroidError, @@ -332,11 +332,13 @@ def root(self) -> nodes.Module: :returns: The root node. """ if not (parent := self.parent): - return self # type: ignore[return-value] # Only 'Module' does not have a parent node. + assert isinstance(self, nodes.Module) + return self while parent.parent: parent = parent.parent - return parent # type: ignore[return-value] # Only 'Module' does not have a parent node. + assert isinstance(parent, nodes.Module) + return parent def child_sequence(self, child): """Search for the sequence that contains this child.