diff --git a/doc/whatsnew/fragments/8735.other b/doc/whatsnew/fragments/8735.other new file mode 100644 index 0000000000..8d8a3109f4 --- /dev/null +++ b/doc/whatsnew/fragments/8735.other @@ -0,0 +1,3 @@ +Fix a crash when a ``nonlocal`` is defined at module-level. + +Closes #8735 diff --git a/pylint/checkers/variables.py b/pylint/checkers/variables.py index 2bd553fa11..5037b9229d 100644 --- a/pylint/checkers/variables.py +++ b/pylint/checkers/variables.py @@ -2913,7 +2913,7 @@ def _check_self_cls_assign(self, node: nodes.Assign) -> None: elt.name for elt in target.elts if isinstance(elt, nodes.AssignName) ) scope = node.scope() - nonlocals_with_same_name = any( + nonlocals_with_same_name = node.scope().parent and any( child for child in scope.body if isinstance(child, nodes.Nonlocal) ) if nonlocals_with_same_name: diff --git a/tests/functional/n/nonlocal_without_binding.py b/tests/functional/n/nonlocal_without_binding.py index 277c7f7ebd..ae8b60677d 100644 --- a/tests/functional/n/nonlocal_without_binding.py +++ b/tests/functional/n/nonlocal_without_binding.py @@ -69,3 +69,7 @@ def inner(): myint += 1 return inner() + + +nonlocal APPLE # [nonlocal-without-binding] +APPLE = 42 diff --git a/tests/functional/n/nonlocal_without_binding.txt b/tests/functional/n/nonlocal_without_binding.txt index 039d07b522..ab31524bcb 100644 --- a/tests/functional/n/nonlocal_without_binding.txt +++ b/tests/functional/n/nonlocal_without_binding.txt @@ -2,3 +2,4 @@ nonlocal-without-binding:29:8:29:18:func.other_func:nonlocal name b found withou nonlocal-without-binding:35:8:35:18:func.other_func2:nonlocal name c found without binding:HIGH nonlocal-without-binding:40:4:40:14:SomeClass:nonlocal name x found without binding:HIGH nonlocal-without-binding:43:8:43:26:SomeClass.func:nonlocal name some_attr found without binding:HIGH +nonlocal-without-binding:74:0:74:14::nonlocal name APPLE found without binding:HIGH