r/Python • • Jul 22 '21

Resource Do not use mutable objects as default arguments in Python

https://medium.com/geekculture/do-not-use-objects-as-default-arguments-in-python-1c940212db2e
1.3k Upvotes

218 comments sorted by

View all comments

Show parent comments

1

u/sumduud14 Jul 23 '21

Once you see it roughly 100 times in your team’s code base it is clearer than a conditional

Implicitly interpreting data structures as boolean in order to check for None is clearer than a conditional?

You seriously believe:

arr = arr or []

Is more clear than:

if arr is None: arr = []

I am astounded that you would claim something so obviously false.

The behaviour of the "or" method also switches around types in a non obvious way if you pass in a falsey value like False or an empty set.

1

u/Smallpaul Jul 23 '21

‘Black’ will reformat your one liner into two.

Coercing all false values to a single type is a feature, not a bug. What circumstance do you see where it will cause a problem?

1

u/sumduud14 Jul 23 '21

Then we can do

arr = [] if arr is None else arr

which will stay a one liner.

It's a problem because it's less clear. Even if you wanted to have the coercion, using ternary is still better and clearer. The or trick is needlessly complex and requires unnecessary thought.

I don't see the benefit of using or here, whereas the cost is clear - it's a non obvious trick that people reading the code might not immediately understand. I notice you didn't try to argue that using or is clearer than using if...

1

u/Smallpaul Jul 24 '21

I did argue that it is clearer in the context of a code base that has standardized on it. Otherwise it’s 50/50 If the person reading the code is an experienced python programmer.

Python’s “or” works that way for a reason. It isn’t an accident. It’s a tool intended to be used in this way.