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'>, [])
>>>
The idiomatic way is:
Noneis a singleton so you can useisoperator for comparison.Your code tests truthness of
list_of_objects(allifandorvariants 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.