Skip to content Skip to sidebar Skip to footer

About The Global Keyword In Python

# coding: utf-8 def func(): print 'x is', x #x = 2 #if I add this line, there will be an error, why? print 'Changed local x to', x x = 50 func() print 'Value of x is

Solution 1:

The trick here is that local names are detected statically:

  • As long as the name x is not assigned in the function, references to x resolve to the the global scope
  • If the name x is assigned anywhere in the function, Python assumes that x is thus a local name everywhere in the function. As a consequence, the first line becomes an error because local name x is used before being assigned.

In other words: assigned name is treated as local everywhere in the function, not just after the point of assignment.

Solution 2:

The global keyword is required only to write to globals.

There is an error because assigning to a variable which is not declared global creates a local variable of that name. You refer to x in that scope before it is assigned to, so you are attempting to read a local variable which has not yet been assigned.

Solution 3:

Python uses fairly typical variable scoping. Non-local variables are visible within a function.

You only need global keyword if you want to assign to a variable within global scope. Also you have to note the difference between global and outer scope. Consider implications:

x = 'global'def f():
    x = 'local in f'def g():
        global x 
        x = 'assigned in g'
    g()
    print x

Upon execution of f() above code will print local in f, while x in global scope is set to 'assigned in g'.


As of Python 3, there is also nonlocal keyword, which allows you assigning to variable from outer scope.

x = 'global'deff():
    x = 'local in f'defg():
        nonlocal x 
        x = 'assigned in g'return g
    print(x)

Upon execution of f() above code will print 'assigned in g(which is the value ofxin local scope off()), while value ofx` in global scope remains untouched.

It's also worth to note, that Python uses lexical (static) scoping, thus following code does not modify the x in the global scope:

x = 'global'deff():
    x = 'local in f'defg():
        nonlocal x 
        x = 'assigned in g'return g
g = f()
g()

Post a Comment for "About The Global Keyword In Python"