Search code examples
pythonglobal-variables

Global variables in python not referenced when later if clause is present


I'm trying to understand why the following code fails, not recognizing the global variable:

xy = 4

def b():
        print(xy)
        if xy is None:
                xy = 2

def a():
        print(xy)
        b()

a()

When running, I get the output:

$ python3 globals-test2.py 
4
Traceback (most recent call last):
  File "globals-test2.py", line 12, in <module>
    a()
  File "globals-test2.py", line 10, in a
    b()
  File "globals-test2.py", line 4, in b
    print(xy)
UnboundLocalError: local variable 'xy' referenced before assignment

Why global xy is not recognized in function b?

Removing the if clause in function b makes the error go away.

Thanks.


Solution

  • This is a well-known gotcha in Python. Any variable that is assigned to in a function is a local for the entire function. If you want the outer xy, you have to say

    global xy

    in the function.

    Note that by "assigned to", I literally mean xy = <value>. If you write xy[0] = value or xy.foo = value, then xy could still be a global without declaring it such.