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
[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