Is a short circuit in nomination statements a good style?

If I understand correctly

myvar = a and b or c 

gives the same result as

 if a: if b: myvar = b else: myvar = c else: myvar = c 

so I think it is more elegant.

I seem to remember how this short-circuit operator was specified in JavaScript code. But is this considered a good style in Python for using short circuits in assignment statements?

+4
source share
2 answers

It really is a matter of opinion, but for the most part, the answer is no. This contradicts several style guides, probably because people tend to think that it means “if a is true, use the value of b, otherwise use the value of c” rather than the real meaning that you publish.

You probably want the new-ish conditional expression syntax instead:

 myvar = b if a else c 
+3
source

In most cases, you want to use a conditional expression instead:

 myvar = b if a else c 

A short circuit is very Pythonic, but just be aware of the pitfalls, where b is false-y; using a short circuit will lead to a different result in this case. In most cases, you do not want to assign c .

Even in this case, you can get the same result with the adjusted condition:

 myvar = b if a and b else c 

Short circuit is great for default values:

 foo = somevar or 'bar' 

or to ensure compliance with the prerequisites:

 foo = somevar and function_raises_exception_if_passed_empty_value(somevar) 
+13
source

Source: https://habr.com/ru/post/1492767/


All Articles