default value in __init__

Chris Rebert clp at rebertia.com
Thu Oct 9 04:12:07 EDT 2008


See Pitfall #5 on http://zephyrfalcon.org/labs/python_pitfalls.html
It also applies to dictionaries (and sets, any mutable object really).

On Thu, Oct 9, 2008 at 1:03 AM, kenneth <kenneth at inwind.it> wrote:
> Dear all,
>
> I have encountered this weird problem.
>
> I have a class definition with an __init__ argument 'd'
> which defaults to {}. This argument is put in the 'self.d'
> attribute at initialization
>
> I create two independent instances of this class; the code
> is as follows.
>
> class C:
>  def __init__(self, i=10, d = {}):

Change 'd = {}' to 'd=None'
Add the line:
if d is None: d = {}

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>    self.d = d
>    self.i = i
>  def get(self):
>    print
>    print self.d
>  def set(self, dval, ival):
>    self.d.update(dval)
>    self.i+=ival
>
> c1=C()
> c1.set({'one':1},3)
> c1.get()
>
> del c1
>
> c2=C()
> c2.set({'two':2},4)
> c2.get()
>
>
> If I run the code I obtain:
>
> {'one': 1}
>
> {'two': 2, 'one': 1}
>
> It seems that the 'self.d' argument of the second instance is the
> same of the 'self.d' of the first (deleted!) instance.
>
> Running the code in a debugger I discovered that, when I enter the
> __init__ at the second initialization, before doing
>
> self.d = d
>
> the 'd' variable already contains the 'self.d' value of the first
> instance and not the default argument {}.
>
> Am I doing some stupid error, or this is a problem ?
>
> Thanks in advance for any help,
> Paolo
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list