Python Gem #3: x or y
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:
NoneFalse0- 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.