Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python style: if statements vs. boolean evaluation

One of the ideas of Python's design philosophy is "There should be one ... obvious way to do it." (PEP 20), but that can't always be true. I'm specifically referring to (simple) if statements versus boolean evaluation. Consider the following:

if words:
    self.words = words
else:
    self.words = {}

versus

self.words = words or {}

With such a simple situation, which is preferable, stylistically speaking? With more complicated situations one would choose the if statement for readability, right?

like image 730
Mike Craig Avatar asked Jun 10 '10 05:06

Mike Craig


2 Answers

"There should be only one" can perfectly well always be true; it's the positive assertion "there is only one" that cannot be -- "should" implies a target, a goal, not the possibility of always reaching it (e.g., for numbers a and b, forbidding either b + a or a + b would be so absurd that there just cannot sensibly be "only one way" in this case).

In your example, I would agree that the or is preferable in sufficiently simple cases (four lines to do what can be done in one clear and readable line is a waste of vertical space) but not for a predicate of any significant complexity. Deciding what has "significant complexity" is, of course, a judgment call.

like image 168
Alex Martelli Avatar answered Sep 22 '22 02:09

Alex Martelli


In this case I'd say "Explicit is better than implicit".

When someone reads your code, they can make a few assumptions. They can assume that "words" can be either an empty dict or one with data in it (missing the case when it is None) In that case, they might be tempted to optimize your code. They might even be right to do it, if it isn't stated anywhere that you can get a None value.

If "words" can in fact be None, I'd try to be clear about that with:

self.words = words
if words is None:
    self.words = {}

Or possibly an "else" instead of unconditional assignment first. In any case, this way you sort of document the fact that None is an expected value for "words".

like image 30
Mattias Nilsson Avatar answered Sep 18 '22 02:09

Mattias Nilsson