eval() and global variables

Juan Pablo Romero Méndez jpablo.romero at gmail.com
Fri Dec 19 08:08:22 CET 2008


The hack given by Peter works fine, except in this case:

>>> def aaaa(fn):
...     f2 = lambda x,y:(x,y,fn(x,y))
...     function = type(f2)
...     f3 = function(f2.func_code,dict())
...     print f3
...
>>> aaaa(lambda x,y:x+y)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in aaaa
TypeError: arg 5 (closure) must be tuple
>>>


Strange...




2008/12/17 Peter Otten <__peter__ at web.de>:
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list