<var> is None vs. <var> == None
J. Cliff Dyer
jcd at sdf.lonestar.org
Tue Jan 27 09:46:42 EST 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,
> etc.)
> >>
> >
> > That entirely depends on whether you wish to test for
> something which
> > *is* None or something with *equals* None. Those two things
> have
> > different meanings.
> >
>
>
> Actually, for None, those two things *are* the same. If
> something
> *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
> system.
>
> Not if someone decided to be a PITA.
>
> >>> class A(object) :
> ... def __eq__(self, other) :
> ... return other is None
> ...
> >>> a = A()
> >>> a == None
> True
> >>> a is None
> False
>
>
or slightly less PITAish:
class EqualThing(object):
def __eq__(self, other):
return True
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
> surprised.
> >
> > 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
> *equal*
> None is if it *is* None.
> None is not a value an object can have, but rather it is a
> (singleton)
> object that can be referenced. Setting something *equal* to
> None is
> accomplished by making it refer to the single None object, at
> which
> point it *is* None.
>
> Gary Herron
>
> >
> >
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
> --
> http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list