I have a questions regarding the inner workings of the global statement in Python. With the syntax
def f():
global x
x = 1
Variable x
is turned into a global variable appears in globals()
and is accessible outside of f
. So far understood.
Until now I assumed, that with global x
the name x
is defined and should reference to a memory address, however if x
is not initialized, such as
def f():
global x
id(x)
a name "x" not defined
error pops up.
Therefore I am wondering what immediate effect the global x
line has in the background,as neither locals, globals, vars
seem to be affected by the line shown by the comparison below:
def test():
global x
print("Vars")
print([i for i in vars().keys() if i[0] != "_"])
print("Globals")
print([i for i in globals().keys() if i[0] != "_"])
print("Locals")
print([i for i in locals().keys() if i[0] != "_"])
x = 1
print("Vars")
print([i for i in vars().keys() if i[0] != "_"])
print("Globals")
print([i for i in globals().keys() if i[0] != "_"])
print("Locals")
print([i for i in locals().keys() if i[0] != "_"])
test()
After global x
the scopes are all empty, and after assignment, x
is rightfully set as global
.
Vars
[]
Globals
['In', 'Out', 'get_ipython', 'exit', 'quit', 'test']
Locals
[]
Vars
[]
Globals
['In', 'Out', 'get_ipython', 'exit', 'quit', 'test', 'x']
Locals
[]
def test():
print("Vars")
print([i for i in vars().keys() if i[0] != "_"])
print("Globals")
print([i for i in globals().keys() if i[0] != "_"])
print("Locals")
print([i for i in locals().keys() if i[0] != "_"])
x = 1
print("Vars")
print([i for i in vars().keys() if i[0] != "_"])
print("Globals")
print([i for i in globals().keys() if i[0] != "_"])
print("Locals")
print([i for i in locals().keys() if i[0] != "_"])
test()
Without global x
it is local
Vars
[]
Globals
['In', 'Out', 'get_ipython', 'exit', 'quit', 'test']
Locals
[]
Vars
['x']
Globals
['In', 'Out', 'get_ipython', 'exit', 'quit', 'test']
Locals
['x']
So basically the question is, where the heck does python save the information of x
going to be global
between definition and assignment.