if not None -v- OR

  • A+
Category:Languages

Let's say we have a dict that will always have keys first_name and last_name but they may be equal to None.

{     'first_name': None,     'last_name': 'Bloggs'  }     

We want to save the first name if it is passed in or save it as an empty string if None is passed in.

first_name = account['first_name'] if account['first_name'] else "" 

-v-

first_name = account['first_name'] or "" 

Both of these work, however, what is the difference behind the scenes? Is one more efficient than the other?

 


result = value if value else "" 

This is the ternary conditional operator and basically equivalent to the following if statement:

if value:     result = value else:     result = "" 

It is very explicit and allows you to describe correctly what condition you require. In this case, it just looks at the truthy value of value, but you could easily expand this to make a strict test against None for example:

result = value if value is not None else "" 

This would for example retain falsy values like False or 0.

value or "" 

This uses the boolean or operator:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So this is basically a way to get the first truthy value (defaulting to the right operand). So this does the same as the value if value else "". Unless the conditional operator, it does not support other checks though, so you can only check for truthiness here.

In your case, where you want to just check against None and fall back to an empty string, there’s no difference at all. Just choose what is most understandable to you. From a “pythonic” point of view, one would probably prefer the or operator, as that’s also a bit shorter.

From a performance standpoint, the conditional operator is slightly more expensive in this case, as this needs to evaluate the dictionary access twice. In practice that won’t be noticeable though, at least not for a dictionary access.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: