Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Confused about singleton-comparison suggestion by pylint

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)

My question is, a is True will check both address and value
and I cannot assume immutable variables will have the same address

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 suggests 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.

>Solution :

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?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading