is implemented with id ?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Wed Sep 5 10:13:30 EDT 2012


On Wed, 05 Sep 2012 05:48:26 -0700, Ramchandra Apte wrote:

> Seeing this thread, I think the is statment should be removed. It has a
> replacement syntax of id(x) == id(y)

A terrible idea.

Because "is" is a keyword, it is implemented as a fast object comparison 
directly in C (for CPython) or Java (for Jython). In the C implementation 
"x is y" is *extremely* fast because it is just a pointer comparison 
performed directly by the interpreter.

Because id() is a function, it is much slower. And because it is not a 
keyword, Python needs to do a name look-up for it, then push the argument 
on the stack, call the function (which may not even be the built-in id() 
any more!) and then pop back to the caller.

And worst, *it doesn't even do what you think it does*. In some Python 
implementations, IDs can be reused. That leads to code like this, from 
CPython 2.7:

py> id("spam ham"[1:]) == id("foo bar"[1:])
True

You *cannot* replace is with id() except when the objects are guaranteed 
to both be alive at the same time, and even then you *shouldn't* replace 
is with id() because that is a pessimation (the opposite of an 
optimization -- something that makes code run slower, not faster).


> and "a==True" should be automatically changed into memory comparison.

Absolutely not. That would be a backward-incompatible change that would 
break existing programs:

py> 1.0 == True
True
py> from decimal import Decimal
py> Decimal("1.0000") == True
True



-- 
Steven



More information about the Python-list mailing list