Article 6BECQ CodeSOD: Python's Tern

CodeSOD: Python's Tern

by
Remy Porter
from The Daily WTF on (#6BECQ)

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), it accomplishes the same thing. And, like any other language with ternaries in it, it opens the chance for some ugly, stupid, and confusing code.

Jakub found this:

welcome_mt = False if rules.get(241) != 'yes' or None else False

There's a lot of code smells packed into this, and let's just tackle the obvious one: no matter what, this sets welcome_mt equal to False in every case- the fact that the condition is jammed between the values makes it harder to see in a quick skim, but the condition is meaningless.

The condition is meaningless in terms of behavior, but the condition is quite meaningful in terms of the WTFs it clearly hides.

Obviously, this rules object is meant to evaluate or otherwise retrieve values from some set of flags, or perhaps even an actual rules engine that executes code and returns results. Each rule is identified by a number, which does a wonderful job making the code more cryptic. Are there at least 241 rules, or is the numbering sparse? What does rule 241 represent? Absolutely no idea.

But even better- wherever these values come from, they come in as strings. Almost certainly, the entire thing is stringly typed, with numeric values also coming in as strings. Whether this data is produced by calling functions at runtime or reading in from a configuration file, it's a clear "we've done a terrible job" signal.

The condition gets even worse, because of that or None on it. None is a falsy value in Python. It adds nothing to this statement, except more static and noise to confuse developers.

I'm honestly amazed at the depths of WTF surfaced in this tiny little line.

otter-icon.png [Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments