eval() and global variables

Peter Otten __peter__ at web.de
Wed Dec 17 09:48:01 CET 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)
>>> k
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined

This is a hack, of course.


More information about the Python-list mailing list