Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected Python variable scope using Walrus Operator := assignment expression [duplicate]

I found the variable scope of the following code to be very unexpected... (coming from other languages where the scope of the scope_var variable would only exist for the span of the IF):

if scope_var := 'exists after IF':
    pass
print(scope_var)

What will be printed?

like image 246
akaButters Avatar asked Nov 17 '25 02:11

akaButters


1 Answers

Outputs: exists after IF

so the variable scope_var now exists outside / past the IF statement.

This was very strange to me, so I thought I post this Q/A for others coming from other languages to learn from. (I Googled quite a few articles, and nothing like this answer came up, so I hope this helps people like myself.)

...

Apparently it's not just the Walrus := assignment expression. It happens with a regular FOR statement as well:

for i in range(3):     
    pass 
print(i) 

Outputs: 2

The variable is available in the surrounding scope.

like image 74
akaButters Avatar answered Nov 19 '25 17:11

akaButters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!