Skip to content

Commit b48259d

Browse files
committed
Fix crash if left hand side of assignment is neither astroid.AssignName nor astroid.AssignAttr
1 parent 970c5d2 commit b48259d

File tree

3 files changed

+21
-1
lines changed

3 files changed

+21
-1
lines changed

pylint/checkers/refactoring/refactoring_checker.py

+5-1
Original file line numberDiff line numberDiff line change
@@ -1407,7 +1407,11 @@ def _append_context_managers_to_stack(self, node: astroid.Assign) -> None:
14071407
if not isinstance(value, astroid.Call):
14081408
continue
14091409
inferred = utils.safe_infer(value.func)
1410-
if not inferred or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS:
1410+
if (
1411+
not inferred
1412+
or inferred.qname() not in CALLS_RETURNING_CONTEXT_MANAGERS
1413+
or not isinstance(assignee, (astroid.AssignName, astroid.AssignAttr))
1414+
):
14111415
continue
14121416
stack = self._consider_using_with_stack.get_stack_for_frame(node.frame())
14131417
varname = (

tests/functional/c/consider/consider_using_with.py

+14
Original file line numberDiff line numberDiff line change
@@ -215,3 +215,17 @@ def my_nested_function():
215215
)
216216
with used_pool:
217217
pass
218+
219+
220+
def test_subscript_assignment():
221+
"""
222+
Regression test for issue https://github.com/PyCQA/pylint/issues/4732.
223+
If a context manager is assigned to a list or dict, we are not able to
224+
tell if / how the context manager is used later on, as it is not assigned
225+
to a variable or attribute directly.
226+
In this case we can only emit the message directly.
227+
"""
228+
job_list = [None, None]
229+
job_list[0] = subprocess.Popen("ls") # [consider-using-with]
230+
job_dict = {}
231+
job_dict["myjob"] = subprocess.Popen("ls") # [consider-using-with]

tests/functional/c/consider/consider_using_with.txt

+2
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,5 @@ consider-using-with:201:4::Consider using 'with' for resource-allocating operati
2222
consider-using-with:202:4::Consider using 'with' for resource-allocating operations:HIGH
2323
consider-using-with:207:4::Consider using 'with' for resource-allocating operations:HIGH
2424
consider-using-with:213:4::Consider using 'with' for resource-allocating operations:HIGH
25+
consider-using-with:229:18:test_subscript_assignment:Consider using 'with' for resource-allocating operations:HIGH
26+
consider-using-with:231:24:test_subscript_assignment:Consider using 'with' for resource-allocating operations:HIGH

0 commit comments

Comments
 (0)