|
|
|
Login
|
Python and Mutable Keyword Arguments
Mutable keyword arguments are created once and once only. Changing keyword arguments inside a method is dangerous, especially in a cluster environment (each node behaviour might become different).
Thanks to Yoshinori Okuji for this tip. Here is an example of code:
>>> def f(toto=[]):
... print toto
... toto.append('titi')
...
>>> f()
[]
>>> f()
['titi']
>>> f()
['titi', 'titi']
>>> f()
['titi', 'titi', 'titi']
>>> def f(toto=None):
... if toto is None: toto = []
... print toto
... toto.append('titi')
...
>>> f()
[]
>>> f()
[]
>>> f()
[]
>>> class c:
... i = 0
...
>>> def f(toto = c()):
... print toto.i
... toto.i = toto.i + 1
...
>>> f()
0
>>> f()
1
>>> f()
2
>>>
This shows that named arguments are not handled as local variables. The second example should be the preferred style if we want to make sure that mutable named parameters are initialized to a default value. Using mutable values as named arguments default values should be used for very specific purpose only. |
|
|