Result of ``a is b''

John Roth newsgroups at jhrothjr.com
Tue Mar 16 08:06:51 EST 2004


"David MacQuigg" <dmq at gain.com> wrote in message
news:gjvc50pkfb1ofgmfd1p39vcsj1g97un7d8 at 4ax.com...
> On 15 Mar 2004 16:32:25 -0800, axelboldt at yahoo.com (Axel Boldt) wrote:
>
> >is there a rationale for the following behavior:
> >
> >  >>> a = (1,2)
> >  >>> b = (1,2)
> >  >>> a is b
> >  False
> >  >>> a = "12"
> >  >>> b = "12"
> >  >>> a is b
> >  True
>
> Here's another one:
> >>> x = 'akdijfkdienlskfi'
> >>> y = 'akdijfkdienlskfi'
> >>> x is y
> True
> >>> x = 'a b'
> >>> y = 'a b'
> >>> x is y
> False
> >>> x == y
> True
> >>>
>
> It has to do with how Python decides which strings to "internalize"
> and make shared objects in order to save space.  This is only a
> problem with immutable objects.  Others cannot be shared like this.
>
> My suggestion is to *never* use 'is' with these objects unless you
> really need the fact that it is faster than '==' and you test it
> thoroughly for the kind of objects you will be comparing.

I'd go a slightly different direction on this: "is" is for physical
identity, "==" is for semantic equivalence. Never mix the two.
You cannot guarantee physical identity across different releases
of CPython, let alone between CPython and Jython (Python on the
Java VM), IronPython (the experimental Python on the .Net CLR)
or PyPy (the even more experimental attempt to rewrite Python in
Python.) And I'm sure I've left out a couple of other environments.

Using "is" is appropriate in only two circumstances:

1) when you're checking if an object you created is bound to
an identifer that's under your control,

and

2) when you're checking one of the few objects that are guaranteed
by the Python specs to be singletons: None, True and False are the
standard suspects in this case.

John Roth


>
> -- Dave
>





More information about the Python-list mailing list