About The Global Keyword In Python
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 tox
resolve to the the global scope - If the name
x
is assigned anywhere in the function, Python assumes thatx
is thus a local name everywhere in the function. As a consequence, the first line becomes an error because local namex
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 of
xin local scope of
f()), while value of
x` 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"