Python vars() global name error

前端 未结 5 745
一整个雨季
一整个雨季 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:22

    vars() within a function gives you the local namespace, just like locals() -- see the docs. Outside of a function (e.g. at the prompt) locals() (and vars() of course) gives you the module's global namespace, just like globals(). As the docs say, trying to assign to a function's local variable through locals() (or equivalently, vars() inside a function) is not supported in Python. If you want to assign to a global variable, as you do when you're at the prompt (or otherwise outside of a function), use globals() instead of vars() (maybe not the cleanest approach -- global variables are understandably frowned upon -- but it does work).

提交回复
热议问题