0

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.

thykl
  • 3
  • 3
  • This question has been answered many times. You could go to the search bar and paste the error "UnboundLocalError: local variable 'xy' referenced before assignment" and get many high quality answers if the linked duplicate is not sufficient. – tdelaney Nov 05 '20 at 17:40
  • I understant I can declare global in b(); but what is surprising is that when the if clause in function b() is not there, xy is considered global; but when the if clause is present, xy is considered local. – thykl Nov 05 '20 at 18:42

3 Answers3

0

the issue with your code is that the variable isn't a global variable. If you want to use them in those functions you would have to either pass them in as a parameter or at the beginning of your function type

global xy

and that will make the variable global in the functions

Jonah.Checketts
  • 54
  • 2
  • 10
0

Since you're using it in a function, declare it a global variable, by adding global xy at the top of your function.

xy = 4

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

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

a()
aTrueParadox
  • 107
  • 2
  • 10
0

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.

Frank Yellin
  • 9,127
  • 1
  • 12
  • 22
  • Thanks; I understand that the assigment in the if clause is what it makes the difference. It was surprising to see that when the if clause in function b() is not there, xy is considered global; but when the if clause is present, xy is considered local. – thykl Nov 05 '20 at 18:46
  • Yeah. All that matters is that `xy = ....` appears somewhere in the function. It doesn't matter whether it's actually executed or not. – Frank Yellin Nov 05 '20 at 18:58