[Python-Dev] Possible bug in class-init, lookin for mentors

Guyzmo z+py+pydev at m0g.net
Fri Apr 21 11:03:57 EDT 2017


On Fri, Apr 21, 2017 at 11:47:24AM +0200, Justus Schwabedal wrote:
> At least I think it's a bug.  Maybe it's a feature..

it's indeed a feature.

> I possibly found a bug in class __init__ and would like to fix it

technically, it's a method. More precisely, it's the constructor method.

> So I'm looking for a mentor to help me.
> 
> class Foo:
>     def __init__(self, bar=[]):
>         self.list = bar
> 
> spam_1 = Foo()
> spam_2 = Foo()
> 
> spam_1.list.append(42)
> print(spam_2.list)`

the argument `bar` of your method is instanciated at the time you're
declaring the method. It's happening once for the the lifetime of the
execution of your code.

By allocating the `bar` reference into the `self.list` member, you're
assigning the same *instance* of that list into the `self.list` member.

So everytime you create a new Foo instance, you're actually assigning
the same `[]` instance into `self.list` which is why, when you mutate
the list, it's happening in all the instances of Foo as well.

I hope it makes sense to you !

-- 
Guyzmo


More information about the Python-Dev mailing list