anekix anekix - 5 months ago 47
Python Question

python or vs explicit if for value assignment

When going through some codebases in python I saw some expressions which roughly translates to the code below:

def foo(a=None):
b = a or {'key1': 'val1',
'key2': 'val2',
'key3': 'val3'

The above can also be written as:

def foo(a=None):
if a is None :
b = {
'key1': 'val1',
'key2': 'val2',
'key3': 'val3'

# now we can use b here

is it just about the coding style or any other benefit that we might have in python considering
evaluation ?

Answer Source

There are differences between the two.

The b = a or {} syntax will assign {} to b if a is any 'falsey' value (i.e. 0, '', False, ...).

Performing an explicit check with:

if a is None:
    b = {}
    b = a

will assign {} to b only if a is None. Any other 'falsey' values for a will ensure the else branch is used.


Having seen your updated question, it seems that the a=None is being assigned in the function def. This is a very common practice to avoid having mutable default values for function arguments. See here for a quick rundown on why this is done.

The standard approach for assigning default parameters in this setting is:

def my_func(x=None):
    if x is None:
        x = [1,2,3,4] #The default, mutable structure that you want to assign to x.

I would avoid taking shortcuts with x = x or [...], unless you're absolutely sure that the user shouldn't pass in a value that will evaluate as false. Even then, better to be explicit.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download