Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Backport maintenance/3.2.x] Fix a false positive for redefined-outer-name #9695

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading