Skip to content

Commit

Permalink
Fix used-before-assignment false positive for walrus operator in di…
Browse files Browse the repository at this point in the history
…ctionary (#8176)
  • Loading branch information
zenlyj authored Feb 10, 2023
1 parent eccba3e commit 32e1545
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions doc/whatsnew/fragments/8125.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Fix ``used-before-assignment`` false positive when the walrus operator
is used with a ternary operator in dictionary key/value initialization.

Closes #8125
5 changes: 5 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -2256,6 +2256,11 @@ def _maybe_used_and_assigned_at_once(defstmt: nodes.Statement) -> bool:
return True
if isinstance(value, nodes.Lambda) and isinstance(value.body, nodes.IfExp):
return True
if isinstance(value, nodes.Dict) and any(
isinstance(item[0], nodes.IfExp) or isinstance(item[1], nodes.IfExp)
for item in value.items
):
return True
if not isinstance(value, nodes.Call):
return False
return any(
Expand Down
13 changes: 13 additions & 0 deletions tests/functional/u/used/used_before_assignment_ternary.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ def function_call_keyword_valid():
var = foo(x=a if (a:='1') else '', y='', z='')
var = foo(x='', y=foo(x='', y='', z=b if (b:='1') else ''), z='')

def dictionary_items_valid():
"""assignment as dictionary keys/values"""
var = {
0: w if (w:=input()) else "",
}
var = {
x if (x:=input()) else "": 0,
}
var = {
0: y if (y:=input()) else "",
z if (z:=input()) else "": 0,
}

def complex_valid():
"""assignment within complex call expression"""
var = str(bar(bar(a if (a:=1) else 0))).lower().upper()
Expand Down

0 comments on commit 32e1545

Please sign in to comment.