changing local namespace of a function

Bo Peng bpeng at rice.edu
Sat Feb 5 15:57:51 EST 2005


Kent Johnson wrote:
> 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}
> 

This is not possible in my case since my dictionary have many more items 
than just x and y. So, if there is are other items in the dictionary

 >>> a = {'x':1, 'y':2, 'else':4}
 >>> f(a,**a)
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
   File "/usr/tmp/python-10176RtT.py", line 1, in ?
     f(a,**a)
TypeError: f() got an unexpected keyword argument 'else'

Bo



More information about the Python-list mailing list