Skip to content

Commit 7e5e4f9

Browse files
Fix a false positive for redefined-outer-name (#9678) (#9695)
When there is a name defined in an exception-handling block which shares the same name as a local variable that has been defined in a function body. Check if the outer node is in the scope of an exception assignment and do not emit ``redefined-outer-name`` if that is the case. Closes #9671 (cherry picked from commit 57ae027) Co-authored-by: Mark Byrne <[email protected]>
1 parent 769ffd2 commit 7e5e4f9

File tree

3 files changed

+34
-0
lines changed

3 files changed

+34
-0
lines changed
Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a false positive for ``redefined-outer-name`` when there is a name defined in an exception-handling block which shares the same name as a local variable that has been defined in a function body.
2+
3+
Closes #9671

pylint/checkers/variables.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1519,6 +1519,15 @@ def visit_functiondef(self, node: nodes.FunctionDef) -> None:
15191519
):
15201520
continue
15211521

1522+
# Suppress emitting the message if the outer name is in the
1523+
# scope of an exception assignment.
1524+
# For example: the `e` in `except ValueError as e`
1525+
global_node = globs[name][0]
1526+
if isinstance(global_node, nodes.AssignName) and isinstance(
1527+
global_node.parent, nodes.ExceptHandler
1528+
):
1529+
continue
1530+
15221531
line = definition.fromlineno
15231532
if not self._is_name_ignored(stmt, name):
15241533
self.add_message(

tests/functional/r/redefined/redefined_except_handler.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,3 +70,25 @@ def func():
7070
# pylint:disable-next=invalid-name, unused-variable
7171
except IOError as CustomException: # [redefined-outer-name]
7272
pass
73+
74+
75+
# https://github.com/pylint-dev/pylint/issues/9671
76+
def function_before_exception():
77+
"""The local variable `e` should not trigger `redefined-outer-name`
78+
when `e` is also defined in the subsequent exception handling block.
79+
"""
80+
e = 42
81+
return e
82+
83+
try:
84+
raise ValueError('outer')
85+
except ValueError as e:
86+
print(e)
87+
88+
89+
def function_after_exception():
90+
"""The local variable `e` should not trigger `redefined-outer-name`
91+
when `e` is also defined in the preceding exception handling block.
92+
"""
93+
e = 42
94+
return e

0 commit comments

Comments
 (0)