跳到内容

unnecessary-dunder-call (PLC2801)

源自 Pylint 代码检查工具。

有时提供修复。

此规则不稳定且处于预览状态。使用需要 --preview 标志。

作用

检查对dunder方法(例如__str____add__)的显式使用。

为什么这不好?

Dunder名称不应被显式调用,并且在大多数情况下,可以替换为内置函数或运算符。

修复安全性

此修复始终是不安全的。当将dunder方法调用替换为运算符或内置函数时,行为可能会以下列方式更改

  1. 类型可能仅实现相关dunder方法的子集。直接调用缺少的dunder方法将返回NotImplemented,但是使用等效运算符会引发TypeError

    class C: pass
    c = C()
    c.__gt__(1)  # before fix: NotImplemented
    c > 1        # after fix: raises TypeError
    
  2. 实例分配的dunder方法将被运算符和内置函数忽略。

    class C: pass
    c = C()
    c.__bool__ = lambda: False
    c.__bool__() # before fix: False
    bool(c)      # after fix: True
    
  3. 即使使用内置类型,行为也可能有所不同。

    (1).__gt__(1.0)  # before fix: NotImplemented
    1 > 1.0          # after fix: False
    

示例

three = (3.0).__str__()
twelve = "1".__add__("2")


def is_greater_than_two(x: int) -> bool:
    return x.__gt__(2)

建议改为

three = str(3.0)
twelve = "1" + "2"


def is_greater_than_two(x: int) -> bool:
    return x > 2