eval() and global variables
Peter Otten
__peter__ at web.de
Wed Dec 17 03:48:01 EST 2008
Juan Pablo Romero Méndez wrote:
> Suppose this function is given:
>
> def f(x,y):
> return x+y+k
>
>
> Is it possible to somehow assign a value to k without resorting to
> making k global?
You can replace the function's global dictionary:
>>> def f(x, y):
... return x+y+k
...
>>> function = type(f)
>>> function(f.func_code, dict(k=1))(2, 3)
6
>>> k
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
This is a hack, of course.
Peter
More information about the Python-list
mailing list