Skip to content

Commit b5e3e71

Browse files
authored
Fix crash on inference of __dict__.items() of an imported module (#1367)
1 parent 26c54d2 commit b5e3e71

File tree

5 files changed

+30
-2
lines changed

5 files changed

+30
-2
lines changed

ChangeLog

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@ Release date: TBA
3131
Closes #1282
3232
Ref #1103
3333

34+
* Fixed crash when trying to infer ``items()`` on the ``__dict__``
35+
attribute of an imported module.
36+
37+
Closes #1085
38+
3439
What's New in astroid 2.9.4?
3540
============================
3641
Release date: TBA

astroid/inference.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -317,6 +317,8 @@ def infer_attribute(self, context=None):
317317

318318
if not context:
319319
context = InferenceContext()
320+
else:
321+
context = copy_context(context)
320322

321323
old_boundnode = context.boundnode
322324
try:
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
import re
2+
3+
4+
class MyModel:
5+
class_attribute = 1
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import models
2+
3+
4+
def func():
5+
for _, value in models.__dict__.items():
6+
if isinstance(value, type):
7+
value.class_attribute += 1

tests/unittest_inference.py

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,7 @@
4848
import unittest
4949
from abc import ABCMeta
5050
from functools import partial
51+
from pathlib import Path
5152
from typing import Any, Callable, Dict, List, Tuple, Union
5253
from unittest.mock import patch
5354

@@ -88,6 +89,7 @@ def get_node_of_class(start_from: nodes.FunctionDef, klass: type) -> nodes.Attri
8889

8990
EXC_MODULE = "builtins"
9091
BOOL_SPECIAL_METHOD = "__bool__"
92+
DATA_DIR = Path(__file__).parent / "testdata" / "python3" / "data"
9193

9294

9395
class InferenceUtilsTest(unittest.TestCase):
@@ -1732,8 +1734,7 @@ def __init__(self):
17321734
"""
17331735
ast = extract_node(code, __name__)
17341736
expr = ast.func.expr
1735-
with pytest.raises(InferenceError):
1736-
next(expr.infer())
1737+
self.assertIs(next(expr.infer()), util.Uninferable)
17371738

17381739
def test_tuple_builtin_inference(self) -> None:
17391740
code = """
@@ -6584,5 +6585,13 @@ def test_relative_imports_init_package() -> None:
65846585
)
65856586

65866587

6588+
def test_inference_of_items_on_module_dict() -> None:
6589+
"""Crash test for the inference of items() on a module's dict attribute.
6590+
6591+
Originally reported in https://github.com/PyCQA/astroid/issues/1085
6592+
"""
6593+
builder.file_build(str(DATA_DIR / "module_dict_items_call" / "test.py"), "models")
6594+
6595+
65876596
if __name__ == "__main__":
65886597
unittest.main()

0 commit comments

Comments
 (0)