Skip to content

Commit

Permalink
Prevent used-before-assignment in pattern matching with a guard (#7922
Browse files Browse the repository at this point in the history
)

(cherry picked from commit bc9f15f)
  • Loading branch information
jacobtylerwalls authored and github-actions[bot] committed Dec 12, 2022
1 parent 1f84ed9 commit 511e39a
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/whatsnew/fragments/5327.false_positive
@@ -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
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
@@ -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
@@ -0,0 +1,2 @@
[testoptions]
min_pyver=3.10

0 comments on commit 511e39a

Please sign in to comment.