Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix crash on inference of __len__ #1234

Merged
merged 5 commits into from
Nov 8, 2021
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions ChangeLog
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ What's New in astroid 2.8.5?
============================
Release date: TBA

* Fix crash on inference of ``__len__``
cdce8p marked this conversation as resolved.
Show resolved Hide resolved

Closes PyCQA/pylint#5244

* Added missing ``kind`` (for ``Const``) and ``conversion`` (for ``FormattedValue``) fields to repr.


Expand Down
2 changes: 1 addition & 1 deletion astroid/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -258,7 +258,7 @@ def object_len(node, context=None):
if (
isinstance(node_frame, scoped_nodes.FunctionDef)
and node_frame.name == "__len__"
and inferred_node is not None
and hasattr(inferred_node, "_proxied")
and inferred_node._proxied == node_frame.parent
cdce8p marked this conversation as resolved.
Show resolved Hide resolved
):
message = (
Expand Down
45 changes: 45 additions & 0 deletions tests/unittest_brain.py
Original file line number Diff line number Diff line change
Expand Up @@ -3126,5 +3126,50 @@ def __len__(self) -> int:
node.inferred()


def test_inference_on_outer_referential_length_check() -> None:
"""
Regression test for https://github.com/PyCQA/pylint/issues/5244
"""
cdce8p marked this conversation as resolved.
Show resolved Hide resolved
node = astroid.extract_node(
"""
class A:
def __len__(self) -> int:
return 42

class Crash:
def __len__(self) -> int:
a = A()
return len(a)

len(Crash()) #@
"""
)
inferred = node.inferred()
assert len(inferred) == 1
assert isinstance(inferred[0], nodes.Const)
assert inferred[0].value == 42


def test_no_attributeerror_on_self_referential_length_check() -> None:
"""
Regression test for https://github.com/PyCQA/pylint/issues/5244
"""
cdce8p marked this conversation as resolved.
Show resolved Hide resolved
with pytest.raises(InferenceError):
node = astroid.extract_node(
"""
class MyClass:
def some_func(self):
return lambda: 42

def __len__(self):
return len(self.some_func())

len(MyClass()) #@
"""
)
assert isinstance(node, nodes.NodeNG)
node.inferred()


if __name__ == "__main__":
unittest.main()