Ben Usman Ben Usman - 4 months ago 39
Python Question

optional list argument "list = list or []" in python

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 []

wim wim

Using None combined with the if-statement for this is usual, it is familiar to python developers and has no weird edge cases. My recommendation is just stick with the convention.

Your proposal of using an or operation here logically deviates from the conventional solution for the edge cases where bool(list_of_vals) == False but list_of_vals is not None, so I would recommend against using that.

Another possible option is to use 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 iterate and index the input container, and vals can happily remain as a tuple.

If you do actually need a list inside the body of the function, for example you need to append or pop items, then you'll add vals = list(vals) as the first line of the function.