2

I see no reason for this code not to work. I could swear that I've written code structured the exact same way without getting this error before, too. This example holds true for both 3.9 and 3.10. I've tried running it in a venv, my global env, and a jupyter notebook.

# this works as expected
my_var = 'xxx'

def my_func():
    print(my_var)

if __name__ == '__main__':
    my_func()
# this does not work
my_var = 'xxx'

def my_func():
    print(my_var)
    if my_var == 'xxx':
        my_var = 'yyy'

if __name__ == '__main__':
    my_func()

Why does adding the if statement break this code? Its inclusion makes the function unable to recognize the variable at all, and it fails when it tries to print it before the if statement.

natebay
  • 53
  • 5
  • 1
    The assignment to `my_var` makes it a local variable. You're trying to read the value before you assign it. – Barmar Oct 19 '22 at 23:57
  • @Barmar Does the parser *read ahead* to determine whether it's a local variable or not? I never realized that. – CrazyChucky Oct 20 '22 at 00:00
  • 1
    Yes, it scans the entire function to see if there are any assignments. It's part of the compiler. – Barmar Oct 20 '22 at 00:00
  • Followin on what Barmar has already said, Python creates the name space for a function at run time. Hence, when you start up your code and the interpreter reads `my_func` it creates a space for `my_var` _inside_ `my_func`, like `my_func.my_var`. Hence, when you access `my_var` insides `my_func` Python goes and looks for `my_func.my_var` which hasn't been defined--it's not he same as `__main__.my_var`. – philosofool Oct 20 '22 at 00:03

0 Answers0