class constructors: class vs. instance defaults

Dan Perl danperl at
Wed Oct 6 19:21:00 EDT 2004

Yes, that's right!  I didn't try it in the context of a function definition 
and thus I only checked that the dict({}) makes a different copy each time. 
I realize now that what happens is that there is now still a 'd' object 
(only in the context of the function) and it is shared by every instance. 
The more I think about it, that's the way it's supposed to work, the default 
value for the argument is calculated only once, when the function is 
defined, no matter how that calculation is made.


"Michael Hoffman" < at> wrote in 
message news:ck1trn$r46$1 at
> Dan Perl wrote:
>> I think that a more "pythonic" way to implement your class is with a 
>> change in the definition of your __init__:
>>     def __init__(self, foo_d=dict({})):
>> This will create a separate copy for each one of your class instances 
>> instead of the common object that you are creating in the definition of 
>> the function.
> Actually it does exactly what the original code did <wink>.
> >>> def x(d=dict({})): return d
> ...
> >>> a = x()
> >>> b = x()
> >>> a
> {}
> >>> b
> {}
> >>> a[3] = 4
> >>> b
> {3: 4}
> Taking out the {} doesn't help either.
> -- 
> Michael Hoffman 

More information about the Python-list mailing list