Skip to content

Commit bc9f15f

Browse files
Prevent used-before-assignment in pattern matching with a guard (#7922)
1 parent e7ef1fd commit bc9f15f

File tree

4 files changed

+16
-0
lines changed

4 files changed

+16
-0
lines changed
Lines changed: 4 additions & 0 deletions
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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2139,6 +2139,7 @@ def _is_variable_violation(
21392139
nodes.AugAssign,
21402140
nodes.Expr,
21412141
nodes.Return,
2142+
nodes.Match,
21422143
),
21432144
)
21442145
and VariablesChecker._maybe_used_and_assigned_at_once(defstmt)
@@ -2239,6 +2240,8 @@ def _maybe_used_and_assigned_at_once(defstmt: nodes.Statement) -> bool:
22392240
"""Check if `defstmt` has the potential to use and assign a name in the
22402241
same statement.
22412242
"""
2243+
if isinstance(defstmt, nodes.Match):
2244+
return any(case.guard for case in defstmt.cases)
22422245
if isinstance(defstmt.value, nodes.BaseContainer) and defstmt.value.elts:
22432246
# The assignment must happen as part of the first element
22442247
# e.g. "assert (x:= True), x"
Lines changed: 7 additions & 0 deletions
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!")
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
[testoptions]
2+
min_pyver=3.10

0 commit comments

Comments
 (0)