changing local namespace of a function

Michael Spencer mahs at telcopartners.com
Fri Feb 4 20:58:30 EST 2005


Bo Peng wrote:
> Michael Spencer wrote:
> 
  >
> 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.
...
> 
> 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?

Try it and see.
> 
> Bo

Compare it with Jeff Shannon's suggestion, and with a lazy dict-wrapper like this:

  >>> class wrapbigdict(object):
  ...     """Lazy attribute access to dictionary keys.  Will not access
  ...         keys that are not valid attribute names!"""
  ...     def __init__(self, mydict):
  ...         object.__setattr__(self, "mydict",mydict)
  ...     def __getattr__(self, attrname):
  ...         return self.mydict[attrname]
  ...     def __setattr__(self, attrname, value):
  ...         self.mydict[attrname] = value
  ...
  ...
  >>> a = {'x':1, 'y':2}
  >>> b = {'x':3, 'y':3}
  ...
  >>> w_a = wrapbigdict(a)
  >>> w_b = wrapbigdict(b)
  ...
  >>> def fun(d):
  ...     d.z = d.x + d.y
  ...
  >>> fun(w_a)
  >>> fun(w_b)
  ...
  >>> w_a.mydict
{'y': 2, 'x': 1, 'z': 3}
  >>> w_b.mydict
{'y': 3, 'x': 3, 'z': 6}
  >>>





More information about the Python-list mailing list