Reference

Ben Finney ben+python at benfinney.id.au
Mon Mar 3 17:17:55 EST 2014


Jerry Hill <malaclypse2 at gmail.com> writes:

> if foo == None:
>     do_stuff()
>
> The only time it would give you a different result from the "is"
> version is if foo was bound to an object that returned True when
> compared with None.

That's right. Python provides this singleton and then recommends you
compare with ‘is’, precisely to protect against pathological cases like
a “return True when compared for equality with None” data type.

Using ‘if foo is None’ means you don't even have to spend time worrying
about such cases.

> And if that were the case, I'm still not convinced that you can tell
> from looking at those two lines of code which one is buggy, except for
> the fact that there has been 20 years of custom saying that comparing
> to None with equality is wrong.

Yes. And because of that widespread convention, it's much more correct
to compare against None with ‘is’.

-- 
 \       “Always do right. This will gratify some people, and astonish |
  `\                                            the rest.” —Mark Twain |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list