Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Difference between 'global' & globals().update(var)

What is the difference between initializing a variable as global var or calling globals().update(var).

Thanks

like image 391
frank Avatar asked Oct 19 '09 17:10

frank


1 Answers

When you say

global var

you are telling Python that var is the same var that was defined in a global context. You would use it in the following way:

var=0
def f():
    global var
    var=1
f()
print(var)
# 1  <---- the var outside the "def f" block is affected by calling f()

Without the global statement, the var inside the "def f" block would be a local variable, and setting its value would have no effect on the var outside the "def f" block.

var=0
def f():
    var=1
f()
print(var)
# 0  <---- the var outside the "def f" block is unaffected

When you say globals.update(var) I am guessing you actually mean globals().update(var). Let's break it apart.

globals() returns a dict object. The dict's keys are the names of objects, and the dict's values are the associated object's values.

Every dict has a method called "update". So globals().update() is a call to this method. The update method expects at least one argument, and that argument is expected to be a dict. If you tell Python

globals().update(var)

then var had better be a dict, and you are telling Python to update the globals() dict with the contents of the var dict.

For example:

#!/usr/bin/env python

# Here is the original globals() dict
print(globals())
# {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None}

var={'x':'Howdy'}
globals().update(var)

# Now the globals() dict contains both var and 'x'
print(globals())
# {'var': {'x': 'Howdy'}, 'x': 'Howdy', '__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__': '/home/unutbu/pybin/test.py', '__doc__': None}

# Lo and behold, you've defined x without saying x='Howdy' !
print(x)
Howdy
like image 93
unutbu Avatar answered Oct 07 '22 04:10

unutbu