Skip to content

Commit 4655b92

Browse files
Prevent used-before-assignment in pattern matching with a guard (#7922) (#7923)
(cherry picked from commit bc9f15f) Co-authored-by: Jacob Walls <[email protected]>
1 parent 1f84ed9 commit 4655b92

File tree

4 files changed

+16
-0
lines changed

4 files changed

+16
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix false-positive for ``used-before-assignment`` in pattern matching
2+
with a guard.
3+
4+
Closes #5327

pylint/checkers/variables.py

+3
Original file line numberDiff line numberDiff line change
@@ -1945,6 +1945,7 @@ def _is_variable_violation(
19451945
nodes.AugAssign,
19461946
nodes.Expr,
19471947
nodes.Return,
1948+
nodes.Match,
19481949
),
19491950
)
19501951
and VariablesChecker._maybe_used_and_assigned_at_once(defstmt)
@@ -2045,6 +2046,8 @@ def _maybe_used_and_assigned_at_once(defstmt: nodes.Statement) -> bool:
20452046
"""Check if `defstmt` has the potential to use and assign a name in the
20462047
same statement.
20472048
"""
2049+
if isinstance(defstmt, nodes.Match):
2050+
return any(case.guard for case in defstmt.cases)
20482051
if isinstance(defstmt.value, nodes.BaseContainer) and defstmt.value.elts:
20492052
# The assignment must happen as part of the first element
20502053
# e.g. "assert (x:= True), x"
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
"""Tests for used-before-assignment with python 3.10's pattern matching"""
2+
3+
match ("example", "one"):
4+
case (x, y) if x == "example":
5+
print("x used to cause used-before-assignment!")
6+
case _:
7+
print("good thing it doesn't now!")
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[testoptions]
2+
min_pyver=3.10

0 commit comments

Comments
 (0)