globals
is actually a function that takes no parameters and returns a dict
, which maps the names of identifiers to their values.
Trying typing just globals()
in a python interpreter and examine the result.
>>> z = 8
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'z': 8, '__doc__': None, '__package__': None}
Notice the 'z': 8
part.
But if you run this code you see actually it takes parameters and change that dict / list / whatever: z = 7 globals()['z'] = 8 print("z=", z) # z= 8
Yup, that's true. The dict
returned by globals()
is where python goes to get the values of global variables, in some sense. Modifying the dict modifies global values directly.
As an FYI, you generally shouldn't be doing stuff like globals()['z'] = 8
. Just do z = 8
if you're in global scope already (ie, not inside of a function/class), and inside a function, do:
def foo():
global z
z = 8