CodeSOD: Python’s Tern

This post was originally published on this site

The Daily WTF

Python is a language underpinned by a philosophy about how programming should work. It’s opinionated. As a result, in the Python world, you’ll hear constant debates over what is and is not “Pythonic”, and you’ll encounter all the weird ways in which the Python philosophy and real-world programming needs conflict: for example, you don’t use switch statements in Python, you put callable functions in a dict instead.

I bring that case up, specifically, because Python’s philosophy is that there should be one correct way to do everything: since if statements handle branches, switch statements are unnecessary. Ternaries are also unnecessary by that rule- but they exist and Python has its own twist on them.

In Python, you can do something like:

foo = bar if condition else goo

Arguably more readable than the traditional ?: glyphs (arguably- I don’t like the condition being between the values, myself),