[Python-Dev] Bug report: empty dictionary as default class argument

Lars Marius Garshol larsga@garshol.priv.no
16 May 2001 10:19:10 +0200


* Idan Sofer
| 
| If a class has an argument with a default of an empty dictionary,
| then all instances of the same class will point to the same
| dictionary, unless the dictionary is explictly defined by the
| constructor.

This is part of the language semantics, and so not a bug. The default
values of optional arguments are evaluated when the function/method is
compiled. You may consider the semantics ill-advised, but it is
intentional.
 
| class foo:
|     
|     def __init__(self,attribs={}):
| 	self.attribs=attribs;
| 	return None;

I usually write this as:

class Foo:

  def __init__(self, attribs = None):
    self.attribs = attribs or {}

--Lars M.