changing local namespace of a function
Kent Johnson
kent3737 at yahoo.com
Sat Feb 5 11:03:51 EST 2005
Bo Peng wrote:
> Dear list,
>
> I have many dictionaries with the same set of keys and I would like to
> write a function to calculate something based on these values. For
> example, I have
>
> a = {'x':1, 'y':2}
> b = {'x':3, 'y':3}
>
> def fun(dict):
> dict['z'] = dict['x'] + dict['y']
>
> fun(a) and fun(b) will set z in each dictionary as the sum of x and y.
>
> My function and dictionaries are a lot more complicated than these so I
> would like to set dict as the default namespace of fun. Is this
> possible? The ideal code would be:
>
> def fun(dict):
> # set dict as local namespace
> # locals() = dict?
> z = x + y
You can part way there using keyword arguments. You just have to use dictionary syntax for changing
values in the dictionary:
>>> def f(d, x=None, y=None):
... d['z'] = x + y
...
>>> a = {'x':1, 'y':2}
>>> b = {'x':3, 'y':3}
>>>
>>> f(a, **a)
>>> a
{'y': 2, 'x': 1, 'z': 3}
>>> f(b, **b)
>>> b
{'y': 3, 'x': 3, 'z': 6}
Kent
More information about the Python-list
mailing list