1

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?

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

good point! I guess the other solution of mine suffers from the same reason.
Indeed, they have the exact same behavior and are just a matter of preference. Don't forget to select the answer if you consider it answers your question the best.
1

a matter of personal style. you could also do

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

just depends on who will be reading your code. personally i'm fine with your second

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.