or as a shortcut for if ... is not None else

Viewed 118

Very often I will have assignments like:

data = {
    'a': var_a if var_a is not None else default_a,
    ...
}

This is somewhat verbose. I think this can be shortened to

data = {
    'a': var_a or default_a,
    ...
}

at least if I know that var_a will not take on a value like 0 or [].

Are there any downsides to using this shorter notation?

2 Answers

Bad if var_a is falsy. This includes the boolean False, zero of any numeric type and a few others. For example, [] or 'foo' prints 'foo'. I like the idea, maybe there is some other Pythonian way to make it work.

var_a or default_a is the usual way to do it when None is treated the same as any 'Falsy' values (0, [], False, ...).

If you specifically need to check for None, you could express it like this:

'a': (var_a,default_a)[var_a is None]

or at least avoid the not by reversing the order

'a': default_a if var_a is None else var_a 

If you're going to do this often, you could make a function to shorten the expression:

def noNone(v,d): d if v is None else v

...

'a': noNone(var_a,default_a)
Related