python - 为什么在 Pylint 认为不正确的条件值中使用 len(SEQUENCE)?

考虑到这个代码片段:

from os import walk

files = []
for (dirpath, _, filenames) in walk(mydir):
    # More code that modifies files
if len(files) == 0: # <-- C1801
    return None

Pylint 对带有 if 语句的行的这条消息感到震惊:

[pylint] C1801:Do not use len(SEQUENCE) as condition value

乍一看,规则 C1801 对我来说并不合理,而 definition on the reference guide没有解释为什么这是一个问题。事实上,它完全称其为错误使用

len-as-condition (C1801): Do not use len(SEQUENCE) as condition value Used when Pylint detects incorrect use of len(sequence) inside conditions.

我的搜索尝试也未能为我提供更深入的解释。我确实理解序列的长度属性可能会被延迟评估,并且 __len__ 可以被编程以产生副作用,但值得怀疑的是,仅此一项是否足以让 Pylint 称这种使用不正确。因此,在我简单地配置我的项目以忽略该规则之前,我想知道我的推理是否遗漏了什么。

什么时候使用 len(SEQ) 作为条件值有问题? Pylint 试图通过 C1801 避免哪些主要情况?

最佳答案

When is the use of len(SEQ) as a condition value problematic? What major situations is Pylint attempting to avoid with C1801?

真的使用 len(SEQUENCE) 没有问题——尽管它可能没有那么高效(参见 chepner’s comment)。无论如何,Pylint 都会检查代码是否符合 PEP 8 style guide其中指出

For sequences, (strings, lists, tuples), use the fact that empty sequences are false.

<b>Yes:</b> if not seq:
     if seq:

<b>No:</b>  if len(seq):
     if not len(seq):

作为偶尔在语言之间穿梭的 Python 程序员,我认为 len(SEQUENCE) 结构更具可读性和明确性(“显式优于隐式”)。但是,在 bool 上下文中使用空序列计算结果为 False 的事实被认为更“Pythonic”。

https://stackoverflow.com/questions/43121340/

相关文章:

python - 为什么使用 Python 的 os 模块方法而不是直接执行 shell 命令?

python - 为什么我不能在 python 中创建一个轮子?

python - Django Admin - 更改标题 'Django administratio

linux - 如何在 Bash 中给定超时后杀死子进程?

python - 如何在 python-3.x 中使用字典格式化字符串?

python - 您需要安装 postgresql-server-dev-X.Y 来构建服务器端扩展

python - 在 Python 中获取大文件的 MD5 哈希

linux - 在远程 Linux 机器上编译 C++ - "clock skew detected

python - 如何将 Pandas 数据添加到现有的 csv 文件中?

linux - 好的 Linux (Ubuntu) SVN 客户端