2

Is the default argument list the same object for all instances?

    class X():
      def __init__(self,a=[]):
        self.member=a   
        print id(a)

    k=X([1,2,3])
    g=X([1,2,3])
    t=X()
    h=X()

The output surprises me:

    140072782781832
    140072782901976
    140072782816536
    140072782816536

As you can see, the id is different when a equals [1,2,3] but stays the same when a is empty. However, if I delete self.member, now the code looks like this:

    class X():
      def __init__(self,a=[]):
        print id(a)

    k=X([1,2,3])
    g=X([1,2,3])
    t=X()
    h=X()

The output becomes like this:

    140033294171528
    140033294171528
    140033294206232
    140033294206232

The id stay the same when a equals [1,2,3].

I am totally confused... Anyone can explain that?

ennuma
  • 23
  • 2

1 Answers1

1

Yes, which is why you are supposed to do

class X():
    def __init__(self, a=None):
        self.a = [] if a is None else a

Edit:

I would point out that

class X():
    def __init__(self,a=[]):
        print(id(a))

k = X([1,2,3])
g = X([1,2,4])   # <- different list values
t = X()
h = X()

also gives

42678232
42678232
42680152
42680152

so I would expect the answer is something like "if you create a list, delete it, and create another list, the odds are good it will reuse the same allocated memory location".

Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • I think `self.a = a or []` would do the same thing, effectively, but be more succinct. (Assuming that a list is expected, and not also something else like a number, which seems to be the case here.) – Waleed Khan Dec 04 '13 at 02:28
  • @WaleedKhan: using `a or []` has the effect of using a *different* list from `a` if `a` happens to be an empty list. If the caller wanted `a` to be a *specific* empty list, then the result might be unexpected. – Greg Hewgill Dec 04 '13 at 02:30
  • Can you explain the second half of the question? Why does removing `self.member = a` change the value of `id(a)`? – John Kugelman Dec 04 '13 at 02:30