For the given code
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
suggests 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
will check both address and value
and I cannot assume immutable variables will have the same address
Thus, changing a == True
to a is True
may lead to incorrect results (a
and True
may have different addresses in memory). Why does pylint
suggest that?
Though
print(hex(id(a)))
print(hex(id(True)))
b = True
print(hex(id(b)))
part gives consistent results. I am not sure if that would work in general.
CodePudding user response:
True
and False
are unique singletons, not immutable. If a
has the value True
, then a
and True
do have the same memory address.
Source: PEP-0285 and In Python are the built in constants True and False unique?
CodePudding user response:
PEP 8 claims that correct way is to use if variable giving following example
if greeting:
and claims that
if greeting == True:
is wrong and
if greeting is True:
is worse.