Search code examples
pythonstyles

Python default (mutable) parameter initialization style


Let's have a function make_sandwich that takes a list of ingredients which has a default value of ['ham', 'ham', 'bacon', 'ham']

def make_sandwich(ingredients=['ham', 'ham', 'bacon', 'ham']):
    print("Making a sandwich with ", ingredients)

However, since this default value is susceptible to this python "mutable default argument" bug feature, we should use an immutable instead like this:

def make_sandwich(ingredients=None):
    # initialized ingredients here
    print("Making a sandwich with ", ingredients)

So here's the question. There're two ways that I am aware of to do this, but I am not sure which one is considered a better practice.

The first one:

if not ingredients:
    ingredients = ['ham', 'ham', 'bacon', 'ham']

The second one:

ingredients = ingredients or ['ham', 'ham', 'bacon', 'ham']

Personally I use the second one more often. Sometimes, I even inline that if the argument is used only once. e.g.

print("Making a sandwich with ", ingredients or ['ham', 'ham', 'bacon', 'ham'])

Is there any solid reason to prefer one over the others?


Solution

  • None of them is actually the right way to do. What if you want to pass an empty list of ingredients?

    A better solution would be

    ingredients = ['ham', 'bacon', 'ham'] if ingredients is None else ingredients