Keyword initialization in Python

Why is the following performed:

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()

      

lead to:

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

      

I don't understand why it doesn't use a new instance of the list when using optional keyword arguments, can that explain this?

0


source to share


3 answers


An empty list in a function definition is created once, during the creation of the function itself. It is not created every time the function is called.

If you want a new one every time, do the following:



class A(object):
    def __init__(self, var=None):
        if var is None:
            var = []
        self._var = var

      

+6


source


It just isn't right. You cannot (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 should 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))

      

+2


source


An empty list in a function definition is created once, during the creation of the function itself. It is not created every time the function is called.

Quite right. To get around this, assign None int function function defiton 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))

      

+1


source







All Articles