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/2.15.x] Prevent used-before-assignment in pattern matching with a guard #7923

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
4 changes: 4 additions & 0 deletions doc/whatsnew/fragments/5327.false_positive
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix false-positive for ``used-before-assignment`` in pattern matching
with a guard.

Closes #5327
3 changes: 3 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -1945,6 +1945,7 @@ def _is_variable_violation(
nodes.AugAssign,
nodes.Expr,
nodes.Return,
nodes.Match,
),
)
and VariablesChecker._maybe_used_and_assigned_at_once(defstmt)
Expand Down Expand Up @@ -2045,6 +2046,8 @@ def _maybe_used_and_assigned_at_once(defstmt: nodes.Statement) -> bool:
"""Check if `defstmt` has the potential to use and assign a name in the
same statement.
"""
if isinstance(defstmt, nodes.Match):
return any(case.guard for case in defstmt.cases)
if isinstance(defstmt.value, nodes.BaseContainer) and defstmt.value.elts:
# The assignment must happen as part of the first element
# e.g. "assert (x:= True), x"
Expand Down
7 changes: 7 additions & 0 deletions tests/functional/u/used/used_before_assignment_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"""Tests for used-before-assignment with python 3.10's pattern matching"""

match ("example", "one"):
case (x, y) if x == "example":
print("x used to cause used-before-assignment!")
case _:
print("good thing it doesn't now!")
2 changes: 2 additions & 0 deletions tests/functional/u/used/used_before_assignment_py310.rc
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[testoptions]
min_pyver=3.10