【问题标题】:Confused about singleton-comparison suggestion by pylint对 pylint 的单例比较建议感到困惑
【发布时间】:2022-11-26 16:26:28
【问题描述】:

对于给定的代码

def greater(n):
    if n > 3:
        res = True
    else:
        res = False

    return res

a = greater(5)
print(hex(id(a)))
print(hex(id(True)))

b = True
print(hex(id(b)))

if  a == True:
    print('yes')
else:
    print('no')

pylint建议pylint_example.py:16:4: C0121: Comparison 'a == True' should be 'a is True' if checking for the singleton value True, or 'a' if testing for truthiness (singleton-comparison)

我的问题是,a is True 将检查both address and value 和我cannot assume immutable variables will have the same address

因此,将 a == True 更改为 a is True 可能会导致不正确的结果(aTrue 在内存中的地址可能不同)。为什么 pylint 这么建议?

尽管

print(hex(id(a)))
print(hex(id(True)))

b = True
print(hex(id(b)))

部分给出一致的结果。我不确定这是否会在一般情况下起作用。

【问题讨论】:

标签: python python-3.x memory-management linter


【解决方案1】:

PEP 8 声称正确的方法是使用 if 变量给出以下示例

if greeting:

并声称

if greeting == True:

是错误的并且

if greeting is True:

更差。

【讨论】:

    【解决方案2】:

    TrueFalse 是唯一的,不是不可变的。如果 a 的值为 True,则 aTrue具有相同的内存地址。

    来源:In Python are the built in constants True and False unique?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多