Is short-circuiting in assignment statements considered good style?

前端 未结 2 1004
清酒与你
清酒与你 2020-12-20 22:36

If I understand correctly

myvar = a and b or c

gives the same result as

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


        
2条回答
  •  星月不相逢
    2020-12-20 22:49

    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)
    

提交回复
热议问题