Python vars() global name error

前端 未结 5 742
一整个雨季
一整个雨季 2021-01-21 08:31

I\'m having a bit of trouble understanding what\'s going wrong with the following function:

def ness():
 pie=\'yum\'
 vars()[pie]=4
 print vars()[pie]
 print yum         


        
5条回答
  •  执笔经年
    2021-01-21 09:28

    It's not safe to modify the dict returned by vars()

    vars([object])¶

    Without an argument, act like locals().

    With a module, class or class instance object as argument (or anything else that has a dict attribute), return that attribute.

    Note

    The returned dictionary should not be modified: the effects on the corresponding symbol table are undefined.

    Your second example is a special case. vars() is equivalent to globals() in the global namespace, and the dict returned by globals() behaves as you would expect ( but is frowned upon )

    >>> id(vars()),id(globals())
    (3085426868L, 3085426868L)
    

提交回复
热议问题