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

Prevent used-before-assignment in pattern matching with a guard #7922

Merged
merged 1 commit into from Dec 12, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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 @@ -2139,6 +2139,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 @@ -2239,6 +2240,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