Python style: if operators are against logical evaluation

One of the ideas of the Python design philosophy is: "There must be one ... obvious way to do this." (PEP 20) , but this may not always be true. I specifically refer to (simple) if and boolean statements. Consider the following:

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

against

 self.words = words or {} 

With such a simple situation, which is preferable, stylistically? In more complex situations, you could choose an if statement for readability, right?

+7
python coding-style if-statement
source share
3 answers

“There should be only one”, it can always be good, this positive statement “there is only one” that cannot be “should” imply a goal, a goal, and not the ability to always achieve it (for example, for numbers a and b , which forbid either b + a or a + b would be so absurd that in this case it’s wise to be “only one way”).

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

+9
source share

In this case, I would say: "Explicit is better than implicit."

When someone reads your code, they can make a few assumptions. They may suggest that the "words" can be either empty or with data in it (there is no case when it is None). In this case, they may be tempted to optimize your code. They may even be right to do this, unless indicated otherwise, that you can get the value None.

If the “words” can actually be “No,” I will try to clarify this:

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

Or perhaps an “else” first instead of an unconditional assignment. In any case, in this way, you have a document confirming that None is the expected value for "words".

+2
source share

(Edited)
ok in case like below i vote for conditional expression

 def somesuch(self, words=None): self.words = words or {} ... 

of course, if you think this will improve readability (can you read it aloud this way?), you can try

 self.words = words if words else {} 
0
source share

All Articles