Interesting behaviour of the assignment

Thomas Wouters thomas at xs4all.net
Thu Dec 28 17:14:07 EST 2000


On Thu, Dec 28, 2000 at 03:12:57PM +0100, Alex Martelli wrote:

> Thus, limit your use of 'is' to cases in which you know
> "object-identity" is indeed meaningful: None, lists, tuples,
> dictionaries, object instances, type-objects, etc.
> (Actually, in the case of None, the semantics of is and
> == are identical, but 'is' can be a tiny little bit faster).
> 
> In practice I find myself using == almost by reflex, e.g.
>     if type(x)==type(0):
> when I KNOW I could safely and reliably write, instead:
>     if type(x) is type(0):
> and perhaps gain a 1/1000th of a second if this is at
> the heart of a heavily-executed loop... '==' is just a
> by-far-too-more-frequent case, except perhaps in the
> specific idion "x is None"!-)

Well, Guido-be-thanked, '==' does an identity check ('is') first. Consider:

>>> class X:
...     def __cmp__(self, other):
...             return -1
...
>>> x1=X()
>>> x1 == x1
1

In other words, 'x == y' first does 'x is y', and if it's true, the result
of the operation is true. Only if 'x is y' is false will it start the
(possibly very expensive) comparison-by-contents operation. The side effect
is that you can never build an object that compares as unequal to itself.
(as above.)

-- 
Thomas Wouters <thomas at xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!




More information about the Python-list mailing list