[Python-Dev] cmp(x,x)

Jewett, Jim J jim.jewett at eds.com
Tue May 18 13:24:56 EDT 2004


Armin Rigo:

	say x has a method __cmp__() that always 
	returns -1.

	>>> x == x             #   x.__cmp__() is called
	False
	>>> x < x              #   x.__cmp__() is called
	True
	>>> cmp(x,x)           #   x.__cmp__() is NOT called
	0
	>>> [x] == [x]         #   x.__cmp__() is NOT called
	True

Note that the last (and only the last) is a change from 2.3
In 2.3, the (identity does not imply equality) trait rolls up 
to containers.

>>> l=[x]
>>> l == l
False

	The only way to explain the semantic is that the expression 
	'x == x' always call the special methods, but built-in functions 
	are allowed to assume that any object compares equal to itself.  

Note that "allowed" is as strong as you can get; is implies ==, but 
does not (currently) imply <= or preclude <.

	Should any of this be documented?

I think so; it is a problem only for pathological cases, but who would 
bother to look up rich comparison in the first place unless they were 
considering at least borderline strangeness.

	An alternative behavior would have been to leave 
	PyObject_RichCompareBool() alone and only insert the short-cut 
	on specific object types' comparison methods

I think it is reasonable for the default to be that identity implies
equality.  Either an explicitly defined __cmp__ should always be
called, or the notes should say that containers can treat identity
as good enough.  

	This is sane as long as no code considers 'nan' as a singleton, 
	or tries to reuse 'nan' objects for different 'nan' values.

Note that float('nan') raises on ValueError on at least the default 
windows 2.3 build; if a NaN is hard to get, I would expect it to be 
reused.

-jJ



More information about the Python-Dev mailing list