Question

I'm very new in Py but I know the syntax function(param1,.. paramN) and I can't understand this:

globals()['z'] = 8

Could not be more 'standar' ?

globals('z') = 8  
# or..
globals(param = 'z') = 8

EDIT: thanks to all for yours answers, I just have a couple of hours playing with Python

In retrospective it's "obvious" globals() returns a instance and I acceding to the index when I write globals('z') but the Dict is returned BY REFERENCE because I can change it just doing:

globals()['z'] = 8

or... just another member suggest:

x = globals(); 
x['z'] = 8

All the "magic" was just a pointer to the index :)

Was it helpful?

Solution

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top