0

While I was learning LEGB scope rule of python, I wanted a deeper understanding of how global works in python. It seems that even if I refer to an undefined variable(Which is also not in builtins), The code doesn't give me an error. Please help me figure out what actually is happening.

def hey():
    x = 1
    def hey2():
        global ew #ew not defined in the module
        x = 2
        print(x)
    hey2()
    print(x)
hey()

OUTPUT: 2
        1
  • read all these answers and you'll have a deeper understanding of how global works, including your current concern: https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them – Adelin Feb 12 '18 at 08:38
  • 1
    Since you are not using the variable, nothing is actually happening. – Stop harming Monica Feb 12 '18 at 08:58
  • Possible duplicate of [Using global variables in a function other than the one that created them](https://stackoverflow.com/questions/423379/using-global-variables-in-a-function-other-than-the-one-that-created-them) – Adelin Feb 12 '18 at 09:17

3 Answers3

1

The keyword global is used to create or update a global variable locally

def hey():
    x = 1
    def hey2():
        global ew #reference to create or update a global variable named ew
        ew=2 # if you comment this global variable will not be created 
        x = 2
        #print(x)
    hey2()
    #print(x)
print '\t ------Before function call-----'
print globals()
hey()

print '\n'
print '\t -----After function call------ '
print globals()

globals() will give you a dictionary of all objects the global scope contains

you can see in the second dictionary ew is present, which was not present in the first dictionary

Pratik Kumar
  • 2,211
  • 1
  • 17
  • 41
1

Yes, the global statement can apply to a name that is not bound (an undefined variable) or even never used. It doesn't create the name, but informs the compiler that this name should be looked up only in a global scope, not in the local scope. The difference shows up in the compiled code as distinct operations:

>>> def foo():
...   global g
...   l = 1
...   g = 2
...
>>> dis.dis(foo)
  3           0 LOAD_CONST               1 (1)
              3 STORE_FAST               0 (l)

  4           6 LOAD_CONST               2 (2)
              9 STORE_GLOBAL             0 (g)
             12 LOAD_CONST               0 (None)
             15 RETURN_VALUE

We see that STORE_FAST was used for a local variable, while STORE_GLOBAL was used for the global variable. There isn't any output for the global statement itself; it only changed how references to g operate.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
-1

Simple example of global variabl in two functions def hey(): global x x = 1 print x hey() # prints 1 def hey2(): global x x += 2 print x hey2() #prints 3

louay_075
  • 37
  • 1
  • 7