Python Gem #3: x or y

Adam Short
Aug 28, 2017 · 1 min read

Last gem covered the ternary operator;

a = <value> if <condition> else <value>

But what about those times where the values can evaluate to False by themselves (e.g they have an element of truthiness)? Well, it can get even simpler.

x = {}
y = { 'c': 1 }
a = x or y # -> a will be equal to { 'c' : 1 }

The line x or y evaluates to x if it’s True, and y if it’s False. Here, True and False are referring to the elements truthiness. The following elements will evaluate as False (and thus the or will default to y ) in this situation:

  • None
  • False
  • 0
  • any empty sequence e.g '' () []
  • any empty mapping e.g {}

An example in which this comes in handy is defaulting from a None value

connect(os.environ.get('DB') or 'sqlite://')

This is a daily series called Python Gems. Each short posts covers a detail or a feature of the python language that you can use to increase your codes readability while decreasing its length.

)

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade