Which is more correct for compaing to None?

Tim Peters tim.one at home.com
Sat May 12 20:51:53 EDT 2001


[Noah]
> Both of these seem to work. Which is more correct?

It depends on what you want to get from the test.

> if foo is None:
>     print 'is'

Succeeds if and only if foo is the same object as None.  This is correct if
that's what you want.

> if foo == None:
>     print '=='

Succeeds if and only if foo compares equal to None.  This is correct if
that's what you want.

"compare equal" includes things like foo being an instance of a class that
defines an _eq__ or __cmp__ method that says foo is equal to None.  The
meaning of "is" cannot be overriden by classes, so *no* class can arrange for
an instance foo to fool the "is None" test.

It's generally a Bad Idea to spoof fundamental builtin objects like None, so
I advise using the "is" test here, just to frustrate your overly clever
coworkers <0.9 wink>.





More information about the Python-list mailing list