changing local namespace of a function
Bo Peng
bpeng at rice.edu
Fri Feb 4 19:46:32 EST 2005
Michael Spencer wrote:
> As you no doubt have discovered from the docs and this group, that isn't
> doable with CPython.
Too bad to know this.
> >>> a = {'x':1, 'y':2}
> >>> b = {'x':3, 'y':3}
> ...
> >>> def funa(x,y, **kw):
> ... del kw #Careful of unwanted names in locals with this approach
> ... z = x + y
> ... return locals()
There are hundreds of items in the dictionary (that will be needed in
the calculation) so passing the whole dictionary is a lot better than
passing individual items.
> Alternatively, you could use exec:
Yes. I thought of using exec or eval. If there are a dozen statements,
def fun(d):
exec 'z = x + y' in globals(), d
seems to be more readable than
def fun(d):
d['z'] = d['x'] + d['y']
But how severe will the performance penalty be?
Bo
More information about the Python-list
mailing list