【发布时间】: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 可能会导致不正确的结果(a 和 True 在内存中的地址可能不同)。为什么 pylint 这么建议?
尽管
print(hex(id(a)))
print(hex(id(True)))
b = True
print(hex(id(b)))
部分给出一致的结果。我不确定这是否会在一般情况下起作用。
【问题讨论】:
-
这回答了你的问题了吗? Boolean identity == True vs is True
-
你的整个功能应该是
return n > 3。其他一切都是不必要的。
标签: python python-3.x memory-management linter