Why do class methods share mutable defaults between instances?

Gustavo Niemeyer niemeyer at conectiva.com
Tue Apr 30 18:59:07 EDT 2002


> class Demo:
>     def __init__(self,name,dict={},list=[]):
[...]

That's not a problem. It's a known behavior. The code "def func(...):" will
be executed just once. It means your dict={} will be executed just once
as well. To understand better, think about this:

def __init__(self, name, dict=func()):

Would you expect func to be executed each time you call the function?

> My intent was that each time Demo was instanciated a new dictionary would be 
> assigned to 'dict' if there was no corresponding argument.  However, the 
> behavior is as though the {} were replaced with a class constant.

It's not replaced by a class constant. It's evaluated, and the resulting
dictionary instance is assigned as the parameter default value.

> In order to avoid this behavior I had to reorganize Demo as follows:
> 
> class Demo2:
>     def __init__(self,name,dict=None,list=None):
>         if dict==None:
>             dict = {}

That's the right way to do it.

> I am wondering if this is a bug or a subtle usage error on my part.  I would 
> expect that syntax on functions would be valid for class methods as well, but 
> in this case you get drastically different behaviors.

I'm not sure what you mean by "different behaviors". That's the way
functions work as well. Have a look:

>>> def demo(a, b={}):
...   b[a] = 1
...   print b
... 
>>> demo("a")
{'a': 1}
>>> demo("b")
{'a': 1, 'b': 1}

-- 
Gustavo Niemeyer

[ 2AAC 7928 0FBF 0299 5EB5  60E2 2253 B29A 6664 3A0C ]





More information about the Python-list mailing list