Assignment with “or” in python

♀尐吖头ヾ 提交于 2019-12-05 08:39:26

问题


Is it considered bad style to assign values to variables like this?

x = "foobar" or None
y = some_variable or None

In the above example, x gets the value 'foobar'.


回答1:


No, it's a common practice. It's only considered bad style for expressions that are considerably longer than yours.




回答2:


The primary danger of doing something like this is the possibility that (in the second case) some_variable is False but not None (the integer 0, for instance) and you don't want to end up with y equal to None in that case.




回答3:


I also feel a bit unconfortable using that kind of expressions. In Learning Python 4ed it is called a "somewhat unusual behavior". Later Mark Lutz says:

...it turns out to be a fairly common coding paradigm in Python: to select a nonempty object from among a fixed-size set, simply string them together in an or expression. In simpler form, this is also commonly used to designate a default...

In fact, they produce concise one-line expressions that help to eliminate line noise from the code.
This behavior is the basis for a form of the if/else ternary operator:

A = Y if X else Z


来源:https://stackoverflow.com/questions/8747740/assignment-with-or-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!