Skip to content

Commit

Permalink
Fix a false positive for redefined-outer-name (#9678)
Browse files Browse the repository at this point in the history
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
  • Loading branch information
mbyrnepr2 authored Jun 4, 2024
1 parent 98307a6 commit 57ae027
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
3 changes: 3 additions & 0 deletions doc/whatsnew/fragments/9671.false_positive
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
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.

Closes #9671
9 changes: 9 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1519,6 +1519,15 @@ def visit_functiondef(self, node: nodes.FunctionDef) -> None:
):
continue

# Suppress emitting the message if the outer name is in the
# scope of an exception assignment.
# For example: the `e` in `except ValueError as e`
global_node = globs[name][0]
if isinstance(global_node, nodes.AssignName) and isinstance(
global_node.parent, nodes.ExceptHandler
):
continue

line = definition.fromlineno
if not self._is_name_ignored(stmt, name):
self.add_message(
Expand Down
22 changes: 22 additions & 0 deletions tests/functional/r/redefined/redefined_except_handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,25 @@ def func():
# pylint:disable-next=invalid-name, unused-variable
except IOError as CustomException: # [redefined-outer-name]
pass


# https://github.com/pylint-dev/pylint/issues/9671
def function_before_exception():
"""The local variable `e` should not trigger `redefined-outer-name`
when `e` is also defined in the subsequent exception handling block.
"""
e = 42
return e

try:
raise ValueError('outer')
except ValueError as e:
print(e)


def function_after_exception():
"""The local variable `e` should not trigger `redefined-outer-name`
when `e` is also defined in the preceding exception handling block.
"""
e = 42
return e

0 comments on commit 57ae027

Please sign in to comment.