pythonlistimmutabilityoptional-arguments

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

Solution

  • 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.