diff options
| author | Claudiu Popa <pcmanticore@gmail.com> | 2019-07-10 11:07:24 +0200 |
|---|---|---|
| committer | Claudiu Popa <pcmanticore@gmail.com> | 2019-07-10 11:07:24 +0200 |
| commit | 3e07ab122282244e73281e32465139ca32beffd2 (patch) | |
| tree | e8f1d0c61e3b23c31d6c79662b0f6425c3b10a6f | |
| parent | f58d3c0c33dadca444938af9cd574d192e6166f6 (diff) | |
| download | astroid-git-3e07ab122282244e73281e32465139ca32beffd2.tar.gz | |
Remove `__class__` from FunctionDef locals, instead look it up in the current scope
Previously `__class__` was added as an implicit local for methods, but that causes some issues
as it now is counted as a local instead of a special object created by the compiler.
A better way to be able to find `__class__` is to look it up in the current scope.
Close PyCQA/pylint#1825
| -rw-r--r-- | astroid/scoped_nodes.py | 15 | ||||
| -rw-r--r-- | astroid/tests/unittest_builder.py | 4 |
2 files changed, 14 insertions, 5 deletions
diff --git a/astroid/scoped_nodes.py b/astroid/scoped_nodes.py index 8af0f0f5..3c45da36 100644 --- a/astroid/scoped_nodes.py +++ b/astroid/scoped_nodes.py @@ -1377,9 +1377,6 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): self.type_comment_returns = type_comment_returns self.type_comment_args = type_comment_args - if isinstance(self.parent.frame(), ClassDef): - self.set_local("__class__", self.parent.frame()) - @decorators_mod.cachedproperty def extra_decorators(self): """The extra decorators that this function can have. @@ -1701,6 +1698,18 @@ class FunctionDef(mixins.MultiLineBlockMixin, node_classes.Statement, Lambda): yield from self.body + def scope_lookup(self, node, name, offset=0): + """Lookup where the given name is assigned.""" + if name == "__class__": + # __class__ is an implicit closure reference created by the compiler + # if any methods in a class body refer to either __class__ or super. + # In our case, we want to be able to look it up in the current scope + # when `__class__` is being used. + frame = self.parent.frame() + if isinstance(frame, ClassDef): + return self, [frame] + return super().scope_lookup(node, name, offset) + class AsyncFunctionDef(FunctionDef): """Class representing an :class:`ast.FunctionDef` node. diff --git a/astroid/tests/unittest_builder.py b/astroid/tests/unittest_builder.py index bd94ee80..9c8ec54c 100644 --- a/astroid/tests/unittest_builder.py +++ b/astroid/tests/unittest_builder.py @@ -718,8 +718,8 @@ class FileBuildTest(unittest.TestCase): self.assertEqual(len(_locals), 5) self.assertEqual(keys, ["a", "autre", "b", "local", "self"]) else: # ListComp variables are no more accessible outside - self.assertEqual(len(_locals), 4) - self.assertEqual(keys, ["__class__", "autre", "local", "self"]) + self.assertEqual(len(_locals), 3) + self.assertEqual(keys, ["autre", "local", "self"]) def test_unknown_encoding(self): with self.assertRaises(exceptions.AstroidSyntaxError): |
