Hot off Python inventor Guido van Rossum’s stunning endorsement of last week’s deep dive into function attributes, here’s a little tidbit from an ongoing series of Python minutiae I’m calling Baby Snakes.

(Before continuing, I should disclaim that this is my personal opinion on a matter of style. Coding is an art—even bad code can be art—and one could easily raise practical and aesthetic arguments against my opinions on code style.)

Using Boolean Expressions

I occasionally see inexperienced (and not-so-inexperienced) developers use this pattern:

#> Don't do this:
if some_value > other_value:
  is_some_value_greater = True
else:
  is_some_value_greater = False

What’s wrong with it? Although syntactically and logically correct, it suggests a novice understanding of the nature of boolean expressions.

An expression is a piece of code that evaluates to a value. 1 + 1 is an expression that evaluates to 2. Function calls are expressions since they always evaluate to a value (even if that value is an implicitly returned None). A boolean expression is an expression that evaluates to True or False. In the above snippet, the code between if and : is a boolean expression.

Evaluating Expressions to a Variable

Everyone feels comfortable assigning the result of a mathematical operation or function call to a variable. As noted above, mathematical operations and function calls are both expressions. Why should boolean expressions be treated any differently?

In place of a multi-line if/else statement, assign the result of the boolean expression directly to the variable:

is_some_value_greater = some_value > other_value

This pattern works with any combination of logical, comparison, identity, and membership operators:

is_equal = some_value == other_value
is_dog = type(fido) is Dog
is_clean = isinstance(thing, BadThing) and (thing not in list_of_things)

Boolean Ternary Expressions

An even less stylish pattern than multi-line if/else statements is misuse of conditional expressions, like this funny one-liner:

#> Don't do this:
is_some_value_greater = True if some_value > other_value else False

Conditional expressions evaluate to either the leftmost or rightmost value depending on whether the expression between if and else evaluates to True or False. It’s redundant to wrap a boolean expression in a conditional expression if that conditional expression is merely returning True or False; you can assign the result of the boolean expression directly to a variable and avoid the conditional expression syntax entirely.



This is the third article in my Baby Snakes series, a collection of Python arcana aimed at intermediate and advanced Python developers. For future updates, follow me on Twitter!