0

I've been bugged by the python function globals(), and I have no idea what is happening.

def foo():
    if False:
        x = 2
    elif True:
        globals()['x'] = 2
        print(x)
        
def foo2():
    if False:
        y = 2
    elif True:
        globals()['x'] = 2
        print(x)

foo2()
print("foo2 function working well")
foo()

This gives me the following results :

2 
foo2 function working well!

---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)
<ipython-input-66-4e0c45e0bd37> in <module>
     14 
     15 foo2()
---> 16 foo()

<ipython-input-66-4e0c45e0bd37> in foo()
      4     elif True:
      5         globals()['x'] = 2
----> 6         print(x, "Working well!")
      7 
      8 def foo2():

UnboundLocalError: local variable 'x' referenced before assignment

So basically, having x defined in the condition before, even if not used, will generate an error afterward. I can't explain why some uninterpreted code can generate an error, and I can't understand why this particular one can have any consequences.

I guess this is in the end just because I don't really get what globals() is doing.

Does anyone have an explanation, or good documentation talking about this?

maciejwww
  • 1,067
  • 1
  • 13
  • 26
hulyce
  • 438
  • 3
  • 15

0 Answers0