Python vars() global name error

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

    [Edit: I must be wrong here, since the 'exec' example works.]

    As everyone points out, it's a bad idea to modify vars(). You can understand the error, though, by realizing that python in some sense doesn't "see" that "yum" is a local. "print yum" is still resolved as a global reference; this happens before any code is executed.

    It's the same reason you get an UnboundLocalError from:

    >>> y = 100
    >>> def foo(x):
    ...   if x == 1:
    ...     y = 10
    ...   print y
    ... 
    >>> foo(1)
    10
    >>> foo(2)
    Traceback (most recent call last):
      File "", line 1, in 
      File "", line 4, in foo
    UnboundLocalError: local variable 'y' referenced before assignment
    

提交回复
热议问题