Legitimate use of the "is" comparison operator?
bruno at modulix
onurb at xiludom.gro
Sat Jun 17 12:29:11 EDT 2006
Mike Duffy wrote:
> I just recently realized that the comparison operator "is" actually
> works for comparing numeric values.
It's only an implementation detail of CPython (and is only true for
small integers - you'll find the limit in the CPython source code), not
part of the language specifications. You should *not* relie on this
behaviour.
> 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,
Don't use it for this neither unless you know exactly what you do. Use
isinstance(obj, klass) instead - and yet better, don't check type at all
if you can avoid it.
> and I was just wondering whether or not
> it is considered bad practice in the Python Community to use it for
> numerics as well.
It's even worse than a bad practice : it's an error.
> Example:
>
> a = range(5)
> b = range(5)
>
> if len(a) is len(b):
> print "They're the same size!"
> else:
> print "They're not the same size!"
>
>>> a = range(32000)
>>> b = range(32000)
>>> len(a) is len(b)
False
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list