Conventional way of dealing with optional list arguments is the following:
def func(list_of_vals = None):
if list_of_vals is None:
list_of_vals = []
...
I wounder if the following (shorter) version has any pitfalls? why nobody do that? is it considered more obscure?
list_of_vals = list_of_vals or []
The pattern if arg is None:
is usual, it is familiar to Python developers and has no weird edge cases. My recommendation is just stick with the convention.
Your proposal using or
logically deviates when bool(list_of_vals) == False
but list_of_vals is not None
, so I would recommend against doing that.
Another possible option is to "duck type" using an empty tuple:
def a(vals=()):
...
Because tuples are immutable, this has none of the pitfalls of the mutable default list. There are many use-cases where you only need to the input container to be indexable and iterable, so vals
can happily remain as a tuple.
There are two cases, you want that the list can be altered outside the function, then the second variant prevents calling a
with:
some_list = []
a(some_list)
print(some_list)
If you want to prevent alternation of the list parameter, you should make a copy inside a
def a(l=()):
l = list(l)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With