views:

144

answers:

3

Why does the following:

class A(object):
    def __init__(self, var=[]):
     self._var = var
     print 'var = %s %s' % (var, id(var))

a1 = A()
a1._var.append('one')

a2 = A()

result in:

var = [] 182897439952
var = ['one'] 182897439952

I don't understand why it is not using a new instance of a list when using optional keyword arguments, can anyone explain this?

+6  A: 

The empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called.

If you want a new one each time, do this:

class A(object):
    def __init__(self, var=None):
        if var is None:
            var = []
        self._var = var
RichieHindle
A cleaner way to write that is (untested): self._var = var or []
wbyoung
That doesn't do the same thing. For instance, "1 or []" is 1, but "0 or []" is []
RichieHindle
+2  A: 

This is simply wrong. You can't (meaningfully) provide a mutable object as a default value in a function declaration.

class A(object):
    def __init__(self, var=[]):
        self._var = var
        print 'var = %s %s' % (var, id(var))

You must do something like this.

class A(object):
    def __init__(self, var=None):
        self._var = var if var is not None else []
        print 'var = %s %s' % (var, id(var))
S.Lott
+1  A: 

The empty list in your function definition is created once, at the time the function itself is created. It isn't created every time the function is called.

Exactly. To work around this assign None int he function definiton and check for None in the function body:

class A(object):
    def __init__(self, var=None):
        if var is None:
            var = []
        self._var = var
        print 'var = %s %s' % (var, id(var))
gabor