changing local namespace of a function

Michael Spencer mahs at telcopartners.com
Fri Feb 4 22:55:03 EST 2005


Nick Coghlan wrote:
> 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.
> 
Oooh - evil indeed, but thanks for the pointer.

I debated including a link to one of the 'writable locals' threads, when I 
settled on not 'doable', but gambled on being probably useful rather than 
certainly accurate.  Just goes to show you can't get away with anything in this 
NG ;-)

Cheers

Michael




More information about the Python-list mailing list