changing local namespace of a function

Nick Coghlan ncoghlan at iinet.net.au
Fri Feb 4 22:51:48 EST 2005


Bo Peng wrote:
> Jeff Shannon wrote:
> 
>>
>> This sounds to me like you're trying to re-implement object orientation.
>>
> 
> I have no control over the big dictionaries. All I need to do is 
> processing them in situ --- that is to say, go into each map and 
> manipulate numbers. Parameter passing should be avoid whenever possible 
> since involved number of items are huge.

No, all parameter passing does is pass a pointer to the dictionary - it doesn't 
copy the dictionary itself.

> It is basically like
> 
>   exec 'statements' in d
> 
> but a function with local dictionary d would be best.

Why? How do you know that the performance is unacceptable?

If you *really* want to execute a function with different locals, then you can do:

Py> def f():
...   print x + y
...
Py> exec f.func_code in dict(x=1, y=2)
3

This is unreliable though, since name binding doesn't work correctly:

Py> def f():
...   z = x + y
...
Py> d = dict(x=1, y=2)
Py> exec f.func_code in d
Py> d['z]
Py> d['z']
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
KeyError: 'z'
Py> exec "z = x + y" in d
Py> d['z']
3

An approach like Michael's is going to be much easier to debug, much easier to 
understand later, and far more reliable all the way along. The performance is 
almost certainly going to be acceptable.

Cheers,
Nick.

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



More information about the Python-list mailing list