Skip to content

Commit 27e3624

Browse files
Fix used-before-assignment false positive for walrus operator in dictionary (#8176) (#8254)
(cherry picked from commit 32e1545) Co-authored-by: Zen Lee <[email protected]>
1 parent 4422094 commit 27e3624

File tree

3 files changed

+22
-0
lines changed

3 files changed

+22
-0
lines changed

doc/whatsnew/fragments/8125.bugfix

+4
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
Fix ``used-before-assignment`` false positive when the walrus operator
2+
is used with a ternary operator in dictionary key/value initialization.
3+
4+
Closes #8125

pylint/checkers/variables.py

+5
Original file line numberDiff line numberDiff line change
@@ -2245,6 +2245,11 @@ def _maybe_used_and_assigned_at_once(defstmt: nodes.Statement) -> bool:
22452245
return True
22462246
if isinstance(value, nodes.Lambda) and isinstance(value.body, nodes.IfExp):
22472247
return True
2248+
if isinstance(value, nodes.Dict) and any(
2249+
isinstance(item[0], nodes.IfExp) or isinstance(item[1], nodes.IfExp)
2250+
for item in value.items
2251+
):
2252+
return True
22482253
if not isinstance(value, nodes.Call):
22492254
return False
22502255
return any(

tests/functional/u/used/used_before_assignment_ternary.py

+13
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,19 @@ def function_call_keyword_valid():
2929
var = foo(x=a if (a:='1') else '', y='', z='')
3030
var = foo(x='', y=foo(x='', y='', z=b if (b:='1') else ''), z='')
3131

32+
def dictionary_items_valid():
33+
"""assignment as dictionary keys/values"""
34+
var = {
35+
0: w if (w:=input()) else "",
36+
}
37+
var = {
38+
x if (x:=input()) else "": 0,
39+
}
40+
var = {
41+
0: y if (y:=input()) else "",
42+
z if (z:=input()) else "": 0,
43+
}
44+
3245
def complex_valid():
3346
"""assignment within complex call expression"""
3447
var = str(bar(bar(a if (a:=1) else 0))).lower().upper()

0 commit comments

Comments
 (0)