python - 通过身份或 bool 运算检查参数是否存在?

标签 python

当检查方法的参数以查看它们是否已设置时,进行身份检查是否符合 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/

相关文章:

python - 通过选择设置 Django IntegerField=...名称

Python:如何使脚本在特定时间每天运行?

Python:在符合给定条件的第一个对象的列表中查找位置

python - 如果 Python 中没有数据传输,如何从标准输入或文件中读取?

python - 如何一次删除多列字符串中的第一个字符?

python - 使用Python导入不同模块中函数的返回值时出错

python - 如何使用 bool 型方形对称 numpy 数组中的真值存储存储索引对?

python - 插入具有唯一列的sqlite表

python - 将目录中的文件批量导入到python脚本中

python - 如何在 View 中排序一组对象