Should I include a default value for the argument passed into the constructor?

Question:

I need to add an additional optional argument from_strings to the constructor.

Does this seem right? Or do I need to add a default value for from_strings?

def __init__(self, size=19, from_strings):
    assert 2 <= size <= 26, "Illegal board size: must be between 2 and 26."
    self.size = size
    self.grid = [['E'] * size for _ in range(size)]
    self.from_strings = from_strings

Because the constructor should be taking this:

b = Board(3, ["O.O", ".@.", "@O."])

Or should it be like this?

def __init__(self, size=19, from_strings=[]):
    assert 2 <= size <= 26, "Illegal board size: must be between 2 and 26."
    self.size = size
    self.grid = [['E'] * size for _ in range(size)]
    self.from_strings = from_strings
Asked By: Anne Tillekeratne

||

Answers:

In general your second proposal is better. However, you have to be aware of what would happen if you had two (or more) classes constructed using the default empty list. Better to default to None then test for that and assign a new (empty) list inside the constructor.

Consider the following:

class A:
    def __init__(self, p=[]):
        self._p = p
    @property
    def p(self):
        return self._p

A1 = A()
A2 = A()

A1.p.append('Hello')

print(A2.p)

Output:

['Hello']

A better approach:

class A:
    def __init__(self, p=None):
        self._p = [] if p is None else p
    @property
    def p(self):
        return self._p

A1 = A()
A2 = A()

A1.p.append('Hello')

print(A2.p)

Output:

[]

Why does this happen?

The default value (the empty list) is constructed once by the Python interpreter. Thus all instances of class A will have a reference to the same empty list. This is avoided in the second approach because a new / discrete empty list is constructed when needed

Answered By: Fred

In your case it is better to use the default value because of predictable function behavior.

In the first case, in addition, you have to swap arguments because first non-default argument should not follow the default argument.

Answered By: Kirill Peresypkin
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.