Legitimate use of the "is" comparison operator?

Fredrik Lundh fredrik at pythonware.com
Sat Jun 17 04:00:00 EDT 2006


Mike Duffy wrote:

> I just recently realized that the comparison operator "is" actually 
> works for comparing numeric values.

except that it doesn't work.

> Now, I know that its intended use is for testing object identity, but
> I have used it for a few other things, such as type checking, and I
> was just wondering whether or not it is considered bad practice in
> the Python Community to use it for numerics as well.

writing broken code is never a good practice.

 >>> a = range(10000)
 >>> if len(a) is len(a):
...     print "same size"
... else:
...     print "not the same size"
...
not the same size

(the reason that it appears to work for small integers is that the 
interpreter is caching the objects for some commonly used values, 
including small integers and one-character strings.  but that's an 
interpreter implementation detail, not something you can rely on).

</F>




More information about the Python-list mailing list