Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

python - Is short-circuiting in assignment statements considered 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 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...