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.