Skip to content

Commit 9dd7851

Browse files
tannewtAWhetter
authored andcommitted
Fix adding incorrect attributes from __init__
These cases in __init__ are fixed: * `local_variable : int = 1` * `local_variable = 1` * `self.foo.bar = 1` (Isn't .bar in the object.) This assumes that the first parameter to __init__ is called "self".
1 parent bedadd4 commit 9dd7851

File tree

3 files changed

+30
-0
lines changed

3 files changed

+30
-0
lines changed

autoapi/_parser.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -267,6 +267,23 @@ def parse_functiondef(self, node):
267267
if node.name == "__init__":
268268
for child in node.get_children():
269269
if isinstance(child, (astroid.nodes.Assign, astroid.nodes.AnnAssign)):
270+
# Verify we are assigning to self.
271+
if isinstance(child, astroid.nodes.Assign):
272+
targets = child.targets
273+
else:
274+
targets = [child.target]
275+
276+
target_ok = True
277+
for target in targets:
278+
if not isinstance(target, astroid.nodes.AssignAttr):
279+
target_ok = False
280+
break
281+
_object = target.expr
282+
if not isinstance(_object, astroid.nodes.Name) or _object.name != "self":
283+
target_ok = False
284+
break
285+
if not target_ok:
286+
continue
270287
child_data = self._parse_assign(child)
271288
result.extend(data for data in child_data)
272289

tests/python/py3example/example/example.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,12 @@ def __init__(self):
9292
self.instance_var: bool = True
9393
"""This is an instance_var."""
9494

95+
self.subobject: object = object()
96+
self.subobject.subobject_variable = 1
97+
98+
local_variable_typed: int = 0
99+
local_variable_untyped = 2
100+
95101
async def async_method(self, wait: bool) -> int:
96102
if wait:
97103
await asyncio.sleep(1)

tests/python/test_pyintegration.py

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -459,6 +459,13 @@ def test_annotations(self, parse):
459459

460460
assert example_file.find(id="example.A.instance_var")
461461

462+
# Locals are excluded
463+
assert not example_file.find(id="example.A.local_variable_typed")
464+
assert not example_file.find(id="example.A.local_variable_untyped")
465+
466+
# Assignments to subobjects are excluded
467+
assert not example_file.find(id="example.A.subobject_variable")
468+
462469
global_a = example_file.find(id="example.global_a")
463470
assert global_a
464471
global_a_value = global_a.find_all(class_="property")

0 commit comments

Comments
 (0)