Search code examples
pythonpython-3.xscope

Unexpected Python variable scope using Walrus Operator := assignment expression


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?


Solution

  • 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.