News   Software   Hardware   Publication   Education   FAQ   Projects   Site Map 
Printable version XML version
Login
Name

Password


Join
Forgot your password?
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.


Nexedi, SARL au capital 30.000 Euros, 270, bd. Clémenceau 59700 Marcq-en-Baroeul
RCS Roubaix Tourcoing 440 047 504 - IBAN: FR76 3002 7175 3900 0410 2760 135
Email: info@nexedi.com - Tel. +33(0)6 62 05 76 14 - Fax. +33(0)3 20 72 99 25
Legal Notice
Powered by ERP5 Open Source ERP, Zope, CPS and Nexedi