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

前端 未结 1 2004
死守一世寂寞
死守一世寂寞 2021-02-05 20:19

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

Thanks

相关标签:
1条回答
  • 2021-02-05 20:44

    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
    
    0 讨论(0)
提交回复
热议问题