This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: discrepancy between str.__cmp__ and unicode.__cmp__
Type: Stage:
Components: Interpreter Core Versions: Python 2.4
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: georg.brandl, pitrou, rhettinger
Priority: normal Keywords:

Created on 2005-08-29 14:54 by pitrou, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg26142 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2005-08-29 14:54
I had the surprise, while wanted to use str.__cmp__ as
the cmp argument to list.sort(), that it seems buggy
compared to unicode.__cmp__, and that these methods
seem implemented quite differently (they have a
different type):

$ python
Python 2.4.1 (#2, Aug 25 2005, 18:20:57)
[GCC 4.0.1 (4.0.1-2mdk for Mandriva Linux release
2006.0)] on linux2
Type "help", "copyright", "credits" or "license" for
more information.
>>> unicode.__cmp__
<slot wrapper '__cmp__' of 'unicode' objects>
>>> str.__cmp__
<method-wrapper object at 0xb7a164ac>
>>> u'a'.__cmp__(u'b')
-1
>>> 'a'.__cmp__('b')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'str' object has no attribute '__cmp__'
>>> unicode.__cmp__(u'a', u'b')
-1
>>> str.__cmp__('a', 'b')
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
TypeError: expected 1 arguments, got 2


Am I missing something ?
msg26143 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2005-08-29 15:16
Logged In: YES 
user_id=1188172

String comparison is done with rich compare methods, namely
__lt__, __le__, __gt__, __ge__ and __eq__, __ne__.

Why str.__cmp__ exists and 'a'.__cmp__ does not, I cannot say.
msg26144 - (view) Author: Antoine Pitrou (pitrou) * (Python committer) Date: 2005-08-29 15:35
Logged In: YES 
user_id=133955

You are right, I also forgot there is a builtin cmp()
function that works like expected. Still str.__cmp__'s
behaviour is a bit puzzling to me...
msg26145 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2005-09-03 17:01
Logged In: YES 
user_id=80475

In the absence of a defined __cmp__ method for string
objects, str.__cmp__ inherits type.__cmp__ which is used for
comparing types.  That is why you can sort a list of types:


>>> sorted([int, complex, float, str, dict, list, tuple])
[<type 'complex'>, <type 'dict'>, <type 'float'>, <type
'int'>, <type 'list'>, <type 'str'>, <type 'tuple'>]
History
Date User Action Args
2022-04-11 14:56:12adminsetgithub: 42316
2005-08-29 14:54:08pitroucreate