Python when to use Global ?


This post explains how and when to use global,  globals(), locals()

      Global keyword is used to tell interpreter that the variable is global in current code block.

Eg:

X = 10  # global var ‘X’

print "X before foo = ",X

def foo():
    global X
    X = 20
    print "X in foo = ",X

foo()
print "X in main = ",X

output
-------
x before foo =  10
x in foo =  20
x in main =  20


When it will be use full ?

Only when you need to modify global variables in local code block(local scope)
If you want just to pass X as argument to other function  no need to use global

X = 10
 
def foo():
    bar(X)
 
def bar(arg):
    print "arg = ",arg
 
foo()
 
What happens if X not declared as ‘global’ ?

Then a new local variable X with scope limited to local will be created. And value of X in global scope is unaffected.

X = 10  # global var ‘X’

print "X before foo = ",X

def foo():

    X = 20
    print "X in foo = ",X

foo()
print "X in main = ",X

output :
-----------
X before foo =  10
X in foo =  20
X in main =  10

Solve this !!

x = 10
def foo():
    print "x in foo = ",x
    if x: x = 8    
 
foo()
print "x in main = ",x

You will get an error "UnboundLocalError: local variable 'x' referenced before assignment"

Answer : When X is assigned some value in local scope python will think like a local variable X has been created, but X was printed before it was assigned some value, that’s why UnboundLocalError will occur.