Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 []
like image 306
Ben Usman Avatar asked Oct 28 '16 21:10

Ben Usman


2 Answers

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.

like image 162
wim Avatar answered Oct 06 '22 00:10

wim


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)
like image 27
Daniel Avatar answered Oct 05 '22 23:10

Daniel