<var> is None vs. <var> == None
J. Cliff Dyer
jcd at sdf.lonestar.org
Tue Jan 27 15:46:42 CET 2009
On Fri, 2009-01-23 at 19:31 -0500, Benjamin Kaplan wrote:
> On Fri, Jan 23, 2009 at 7:28 PM, Gary Herron
> <gherron at islandtraining.com> wrote:
> Steven D'Aprano wrote:
> > On Fri, 23 Jan 2009 14:58:34 -0500, Gerald Britton wrote:
> >> Hi -- Some time ago I ran across a comment recommending
> using <var> is
> >> None instead of <var> == None (also <var> is not None,
> > That entirely depends on whether you wish to test for
> something which
> > *is* None or something with *equals* None. Those two things
> > different meanings.
> Actually, for None, those two things *are* the same. If
> *equals* None, it also *is* None. This is a consequence of
> the fact
> that there is only ever one value of None anywhere in the
> Not if someone decided to be a PITA.
> >>> class A(object) :
> ... def __eq__(self, other) :
> ... return other is None
> >>> a = A()
> >>> a == None
> >>> a is None
or slightly less PITAish:
def __eq__(self, other):
Could be a useful sentinel value in some cases.
> > I wonder, do newbies actually get the impression from
> somewhere that "is"
> > is a synonym for "=="?
> Yes. Such questions pop up regularly, and are usually dealt
> with quickly.
> >> My own
> >> testing indicates that the former beats the latter by about
> 30% on
> >> average. Not a log for a single instruction but it can add
> up in large
> >> projects.
> > If you have a "large" project where the time taken to do
> comparisons to
> > None is a significant portion of the total time, I'd be very
> > var is None is a micro-optimization, but that's not why we
> do it. We do
> > it because usually the correct test is whether var *is* None
> and not
> > merely equal to None. Any random object might happen to
> equal None
> > (admittedly most objects don't), but only None is None.
> You don't have that quite right. The only way something can
> None is if it *is* None.
> None is not a value an object can have, but rather it is a
> object that can be referenced. Setting something *equal* to
> None is
> accomplished by making it refer to the single None object, at
> point it *is* None.
> Gary Herron
More information about the Python-list