Skip to content

Commit ffdedfe

Browse files
Prevent used-before-assignment for variables defined in assignment expressions (#7847)
1 parent a6a5446 commit ffdedfe

File tree

3 files changed

+9
-8
lines changed

3 files changed

+9
-8
lines changed

pylint/checkers/variables.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -738,14 +738,14 @@ def _exhaustively_define_name_raise_or_return(
738738
if any(node.nodes_of_class(nodes.Break)):
739739
return True
740740

741-
# If there is no else, then there is no collectively exhaustive set of paths
742-
if not node.orelse:
743-
return False
744-
745741
# Is there an assignment in this node itself, e.g. in named expression?
746742
if NamesConsumer._defines_name_raises_or_returns(name, node):
747743
return True
748744

745+
# If there is no else, then there is no collectively exhaustive set of paths
746+
if not node.orelse:
747+
return False
748+
749749
return NamesConsumer._branch_handles_name(
750750
name, node.body
751751
) and NamesConsumer._branch_handles_name(name, node.orelse)

tests/functional/u/undefined/undefined_variable_py38.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ def expression_in_ternary_operator_inside_container_wrong_position():
182182
z = z + 1
183183

184184

185-
if (never_defined := False):
186-
pass
187-
print(never_defined) # [used-before-assignment]
185+
if (defined := False):
186+
NEVER_DEFINED = 1
187+
print(defined)
188+
print(NEVER_DEFINED) # [used-before-assignment]

tests/functional/u/undefined/undefined_variable_py38.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,4 @@ used-before-assignment:140:10:140:16:type_annotation_used_improperly_after_compr
88
used-before-assignment:147:10:147:16:type_annotation_used_improperly_after_comprehension_2:Using variable 'my_int' before assignment:HIGH
99
used-before-assignment:177:12:177:16:expression_in_ternary_operator_inside_container_wrong_position:Using variable 'val3' before assignment:HIGH
1010
used-before-assignment:181:9:181:10::Using variable 'z' before assignment:HIGH
11-
used-before-assignment:187:6:187:19::Using variable 'never_defined' before assignment:CONTROL_FLOW
11+
used-before-assignment:188:6:188:19::Using variable 'NEVER_DEFINED' before assignment:CONTROL_FLOW

0 commit comments

Comments
 (0)