2

I have function declaration like:

def function(list_of_objects = None)

and if *list_of_objects* not passed (is None) I need to define it like empty list. The explicit way is:

def function(list_of_objects = None):
    if not list_of_objects:
        list_of_objects = list()

or

def function(list_of_objects = None):
    list_of_objects = list() if not list_of_objects else list_of_objects

Does above code equals the next one?

def function(list_of_objects = None):
    list_of_objects = list_of_objects or list()

I tested it, but I'm still not sure

>>> def func(my_list = None):
...     my_list = my_list or list()
...     print(type(my_list), my_list)
... 
>>> func()
(<type 'list'>, [])
>>> func(['hello', 'world'])
(<type 'list'>, ['hello', 'world'])
>>> func(None)
(<type 'list'>, [])
>>> 
atomAltera
  • 1,702
  • 2
  • 19
  • 38

3 Answers3

7

No, since None is not the only false object. Also included are [], (), 0, and of course False.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • `>>> 0 or 42` `42` `>>> [] or 42` `42` `>>> () or 42` `42` `>>> False or 42` `42` – Ignacio Vazquez-Abrams Jan 20 '13 at 23:55
  • A or B returns B if both are *not True*, so in my case, I think, I can use list() in place of B. I ask you, does *list_of_objects = list() if list_of_objects else list_of_objects* makes the same thing? May be there are some hidden issues? (question edited) – atomAltera Jan 20 '13 at 23:59
  • Empty list in boolean context returns False. Similarly, None in boolean context returns False. You would not be able to distinguish empty list from None when using the code from your original question. Because of that you must test `... is None`. – pepr Jan 21 '13 at 07:49
3

The idiomatic way is:

def function(list_of_objects=None):
    if list_of_objects is None:
        list_of_objects = []

None is a singleton so you can use is operator for comparison.

Your code tests truthness of list_of_objects (all if and or variants are equivalent in this case). The following values are considered false in Python:

  • None

  • False

  • zero of any numeric type, for example, 0, 0.0, 0j.

  • any empty sequence, for example, '', (), [].

  • any empty mapping, for example, {}.

  • instances of user-defined classes, if the class defines a __bool__() or __len__() method, when that method returns the integer zero or bool value False.

All other values are considered true — so objects of many types are always true.

jfs
  • 399,953
  • 195
  • 994
  • 1,670
2

The usual practice is:

def function(list_of_objects=None):
    if list_of_objects is None:
        list_of_objects = []
    ...

Use None because it is easy to distinguish from other false values such as an empty list or an empty tuple.

Use an is None test instead of equality test because None is a singleton (this is the preferred practice, per PEP 8).

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485