当检查方法的参数以查看它们是否已设置时,进行身份检查是否符合 pythonic:
def doThis(arg1, arg2=None):
if arg2 is None:
arg2 = myClass()
或者是使用短路 bool 值的正确形式:
def doThis(arg1, arg2=None):
arg2 = arg2 or myClass()
支持前者,PEP 8状态:
Comparisons to singletons like None should always be done with is or is not , never the equality operators. Also, beware of writing if x when you really mean if x is not None -- e.g. when testing whether a variable or argument that defaults to None was set to some other value. The other value might have a type (such as a container) that could be false in a boolean context!
另一方面,来自 Google style guide :
Use the "implicit" false if at all possible. ...
但同时指出...
Never use == or != to compare singletons like None. Use is or is not.
这是否适用于“None”,因为它的计算结果始终为 False,和/或在幕后相当于 ==/!= 的 bool 比较?
编辑: 要回答最后一个问题,“或”在幕后似乎并不等同于“==”:
In [17]: timeit.timeit("1 or None", number=100000000)
Out[17]: 2.0310521125793457
In [18]: timeit.timeit("1 is None", number=100000000)
Out[18]: 2.618263006210327
In [19]: timeit.timeit("1 == None", number=100000000)
Out[19]: 4.554893970489502
最佳答案
考虑如果 arg2
等于 "Falsish" value 会发生什么例如零(或空字符串、列表、元组、字典或集合——仅举几例)。然后
arg2 = arg2 or myClass()
会将 arg2
设置为 myClass()
,即使 arg2=0
可能是 arg2
的预期值>。所以always use is
to determine if arg2
is None .
关于python - 通过身份或 bool 运算检查参数是否存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30633225/