Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is short-circuiting in assignment statements considered good style?

Tags:

python

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 guess it's more elegant.

I seem to remember seeing this kind of short-circuit assignment statement in JavaScript code. But is it considered good style in Python to use short-circuiting in assignment statements?

like image 558
KnewB Avatar asked Jul 22 '13 18:07

KnewB


2 Answers

Most of the time, you then want to use a conditional expression instead:

myvar = b if a else c

Short-circuiting is very Pythonic however, just be aware of the pitfalls where b is false-y; using short-circuiting will result in different result in that case. Most of the time, you do not want to assign c instead.

Even in that case, you can still get the same result with an adjusted condition:

myvar = b if a and b else c

Short-circuiting is great for defaults:

foo = somevar or 'bar'

or for making sure pre-conditions are met:

foo = somevar and function_raises_exception_if_passed_empty_value(somevar)
like image 74
Martijn Pieters Avatar answered Sep 28 '22 00:09

Martijn Pieters


This is really an opinion question, but for the most part, the answer is no. It goes against multiple style guides, probably because people tend to think it means "if a is true, use the value of b, otherwise use the value of c" rather than the real meaning, which is what you posted.

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

myvar = b if a else c
like image 36
the paul Avatar answered Sep 27 '22 22:09

the paul