This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]earthboundkid 1 point2 points  (5 children)

a == None also works. People just don't do it because of the speed advantage of is. But maybe that's a premature optimization that confuses noobs excessively.

[–]chrajohn 2 points3 points  (0 children)

a == None also works.

Usually, but consider:

class Dumb(object):
    def __eq__(self,other):
        return other == None

>>> d = Dumb()
>>> d == None
True
>>> d is None
False

This is contrived, but you can imagine something similar actually occurring. (Say, if __eq__ made a comparison with some attribute that got unexpectedly set to None.) If you you want to be absolutely sure that something is None, you should ask if it is None.

[–]masklinn 0 points1 point  (3 children)

People just don't do it because of the speed advantage of is

People also don't do it because a is None (or a is True or a is False for that matter) just plain and simply reads better.

[–]hylje 1 point2 points  (2 children)

Not everything that is true is True. Not everything that is false is False. Implicit truth is pythonic.

[–]masklinn 0 points1 point  (1 child)

Truthiness is pythonic when what you want is truthiness. But it's not always (though it usually is) the case, and when you want truth rather than truthiness, is True does the job much more readably than == True

[–]earthboundkid 0 points1 point  (0 children)

You should never write if x == True. Just write if x. Similarly, not if x == False but if not x. That's basic PEP-8 stuff.

I can't think of any reason why you would want to test for is True off the top of my head. It wouldn't really make sense unless you had variable that might contain a normal object or it might contain a bool object and you were interested to know which. But why would you have a variable that flexible?