changing local namespace of a function

Nick Coghlan ncoghlan at iinet.net.au
Fri Feb 4 22:39:56 EST 2005


Michael Spencer wrote:
>> def fun(dict):
>>   # set dict as local namespace
>>   # locals() = dict?
>>   z = x + y
> 
> As you no doubt have discovered from the docs and this group, that isn't 
> doable with CPython.

Not entirely impossible:

Py> def f(d):
...   exec "locals().update(d)"
...   return x + y
...
Py> f(dict(x=1, y=2))
3

Due to the way 'exec' is implemented, modifications to locals() inside an exec 
statement actually take effect (basically, they're freeloading on the code which 
allows 'exec "x = 1"' to work properly).

This is an evil, evil hack and almost certainly not what anyone should be doing. 
Also, variables created this way will be slower than normal variables due to the 
way the associated code works.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list