473,605 Members | 2,520 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Would there be support for a more general cmp/__cmp__

I was wondering how people would feel if the cmp function and
the __cmp__ method would be a bit more generalised.

The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.

So I thought that either cmp could return None in this
case or throw a specific exception. People writing a
__cmp__ method could do the same.

--
Antoon Pardon
Oct 20 '05 #1
39 2794
Antoon Pardon wrote:
The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.


If that is the case then you implement __eq__ and __ne__ to return
True/False and make cmp throw an exception. I don't see any need to extend
the cmp protocol.
Oct 20 '05 #2
Op 2005-10-20, Duncan Booth schreef <du**********@i nvalid.invalid> :
Antoon Pardon wrote:
The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.


If that is the case then you implement __eq__ and __ne__ to return
True/False and make cmp throw an exception. I don't see any need to extend
the cmp protocol.


That is not sufficient. There are domains where an order exists, but not
a total order. So for some couples of elements it is possible to say
one is less than the other, but not for all such couples.

Your solution wouldn't allow for such a case.

--
Antoon Pardon
Oct 20 '05 #3
Antoon Pardon wrote:
Op 2005-10-20, Duncan Booth schreef <du**********@i nvalid.invalid> :
Antoon Pardon wrote:
The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.


If that is the case then you implement __eq__ and __ne__ to return
True/False and make cmp throw an exception. I don't see any need to
extend the cmp protocol.


That is not sufficient. There are domains where an order exists, but
not a total order. So for some couples of elements it is possible to
say one is less than the other, but not for all such couples.

Your solution wouldn't allow for such a case.


I don't see why not. If an ordering exists then __cmp__ returns a result
otherwise it throws an exception. So long as you define __eq__ and __ne__,
__cmp__ is never called when checking for equality.
Oct 20 '05 #4
Antoon Pardon wrote:
Op 2005-10-20, Duncan Booth schreef <du**********@i nvalid.invalid> :
Antoon Pardon wrote:

The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.


If that is the case then you implement __eq__ and __ne__ to return
True/False and make cmp throw an exception. I don't see any need to extend
the cmp protocol.

That is not sufficient. There are domains where an order exists, but not
a total order. So for some couples of elements it is possible to say
one is less than the other, but not for all such couples.

Your solution wouldn't allow for such a case.


Wouldn't the full power of rich comparisons be enough? See section 3.3.1
in Python Reference Manual:

http://www.python.org/doc/2.4.2/ref/customization.html

See methods __lt__, __le__, __eq__, __ne__, __gt__, __ge__.

/MiO
Oct 20 '05 #5
Op 2005-10-20, Mikael Olofsson schreef <mi****@isy.liu .se>:
Antoon Pardon wrote:
Op 2005-10-20, Duncan Booth schreef <du**********@i nvalid.invalid> :
Antoon Pardon wrote:
The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.

If that is the case then you implement __eq__ and __ne__ to return
True/False and make cmp throw an exception. I don't see any need to extend
the cmp protocol.

That is not sufficient. There are domains where an order exists, but not
a total order. So for some couples of elements it is possible to say
one is less than the other, but not for all such couples.

Your solution wouldn't allow for such a case.


Wouldn't the full power of rich comparisons be enough? See section 3.3.1
in Python Reference Manual:

http://www.python.org/doc/2.4.2/ref/customization.html

See methods __lt__, __le__, __eq__, __ne__, __gt__, __ge__.


Sure, but it would also be rather cumbersome. It is not uncommon
that a general compare function which could give you one of
four results: one_less_two, one_equal_two, one_greater_two or
one_unequal_two , wouldn't differ much from each of those six
comparison methods. So you either write about six times the
same code or you have to do something like the following:

class partial_order:

def __compare(self, other):
...
return ...

def __lt__(self, other):
return self.__compare( other) == one_less_two

def __le__(self, other):
return self.__compare( other) in [one_less_two, one_equal_two]

def __eq__(self, other):
return self.__compare( other) == one_equal_two

def __ne__(self, other):
return self.__compare( other) == one_unequal_two

def __gt__(self, other):
return self.__compare( other) == one_greater_two

def __ge__(self, other):
return self.__compare( other) in [one_greater_two , one_equale_two]
And then you still wouldn't get a usefull result from:

delta = cmp(e1, e2)

--
Antoon Pardon
Oct 20 '05 #6
Antoon Pardon wrote:
I was wondering how people would feel if the cmp function and
the __cmp__ method would be a bit more generalised.

The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.

So I thought that either cmp could return None in this
case or throw a specific exception. People writing a
__cmp__ method could do the same.

The current behaviour is, of course, by design: """The operators <, >,
==, >=, <=, and != compare the values of two objects. The objects need
not have the same type. If both are numbers, they are converted to a
common type. Otherwise, objects of different types always compare
unequal, and are ordered consistently but arbitrarily."""

Personally I'm still not convinced that your requirement reflects a
substantial use case (but then I'm getting used to that ;-). Just
because an ordering is partial that doesn't mean that two instances of a
class shouldn't be compared.

What would you have Python do when the programmer tries to perform an
invalid comparison (i.e. what are the exact semantics imposed when
__cmp__() returns None/raises an exception)?

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Oct 20 '05 #7
Op 2005-10-20, Steve Holden schreef <st***@holdenwe b.com>:
Antoon Pardon wrote:
I was wondering how people would feel if the cmp function and
the __cmp__ method would be a bit more generalised.

The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.

So I thought that either cmp could return None in this
case or throw a specific exception. People writing a
__cmp__ method could do the same.
The current behaviour is, of course, by design: """The operators <, >,
==, >=, <=, and != compare the values of two objects. The objects need
not have the same type. If both are numbers, they are converted to a
common type. Otherwise, objects of different types always compare
unequal, and are ordered consistently but arbitrarily."""

Personally I'm still not convinced that your requirement reflects a
substantial use case (but then I'm getting used to that ;-). Just
because an ordering is partial that doesn't mean that two instances of a
class shouldn't be compared.


I'm not suggesting that they shouldn't be compared.
What would you have Python do when the programmer tries to perform an
invalid comparison (i.e. what are the exact semantics imposed when
__cmp__() returns None/raises an exception)?


My appologies, I should have been more complete.

What I want is a way to say that all of the following are False:

a < b, a <= b, a == b, a > b, a >= b

and that only the following is True:

a != b
So if a coder writes one of the comparisons and as a result python
calls the __cmp__ method on one of the terms which would return
either None or raise an exceptions I would like it to reflect
the above behaviour.

--
Antoon Pardon
Oct 20 '05 #8
On Thursday 20 October 2005 11:53, Steve Holden wrote:
Personally I'm still not convinced that your requirement reflects a
substantial use case (but then I'm getting used to that ;-). Just
because an ordering is partial that doesn't mean that two instances of a
class shouldn't be compared.
C++ has a cmp template function which can be implemented to define a total
ordering for one type. This can be reliably used by implementations of
ordered tree containers (for example) so that this container template class
can only be instantiated for holding types that provide this comparison
template function.

One disadvantage is that these template container classes can only hold one
type.

ZODB's BTrees work in a similar way but use the regular python comparison
function, and the lack of a guarantee of a total ordering can be a liability.
Described here in 2002, but I think same is true today:
http://mail.zope.org/pipermail/zodb-...ry/002304.html

A BTree might contain two objects that are incomparable. That is, they raise
an exception when compared. However the user will not know this if by
coincidence the BTree implementation has never needed to compare these two
objects.

Now removing a third object from the container such that these two
incomparable objects are adjacent in the BTree. There is a possibility that
an exception might be raised when *reading* content from the BTree, since the
BTree implementation now might need to compare this pair of objects.
What would you have Python do when the programmer tries to perform an
invalid comparison (i.e. what are the exact semantics imposed when
__cmp__() returns None/raises an exception)?


Its too late to handle this by the time a specific comparison method of an
individual object is being called. If you need a total ordering across a
domain of objects then you need to involve some representation of that domain
as a whole.
--
Toby Dickenson
Oct 20 '05 #9
Antoon Pardon wrote:
Op 2005-10-20, Steve Holden schreef <st***@holdenwe b.com>:
Antoon Pardon wrote:
I was wondering how people would feel if the cmp function and
the __cmp__ method would be a bit more generalised.

The problem now is that the cmp protocol has no way to
indicate two objects are incomparable, they are not
equal but neither is one less or greater than the other.

So I thought that either cmp could return None in this
case or throw a specific exception. People writing a
__cmp__ method could do the same.

The current behaviour is, of course, by design: """The operators <, >,
==, >=, <=, and != compare the values of two objects. The objects need
not have the same type. If both are numbers, they are converted to a
common type. Otherwise, objects of different types always compare
unequal, and are ordered consistently but arbitrarily."""

Personally I'm still not convinced that your requirement reflects a
substantial use case (but then I'm getting used to that ;-). Just
because an ordering is partial that doesn't mean that two instances of a
class shouldn't be compared.

I'm not suggesting that they shouldn't be compared.

Sorry, I thought that was the meaning of "The problem now is that the
cmp protocol has no way to indicate two objects are incomparable".
What would you have Python do when the programmer tries to perform an
invalid comparison (i.e. what are the exact semantics imposed when
__cmp__() returns None/raises an exception)?

My appologies, I should have been more complete.

What I want is a way to say that all of the following are False:

a < b, a <= b, a == b, a > b, a >= b

and that only the following is True:

a != b
So if a coder writes one of the comparisons and as a result python
calls the __cmp__ method on one of the terms which would return
either None or raise an exceptions I would like it to reflect
the above behaviour.

Ergo: use rich comparisons.

regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006 www.python.org/pycon/

Oct 20 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
4904
by: Jan-Erik Meyer-Lütgens | last post by:
In the Python Language Reference, I found the following statements about using objects as dictionary keys: 1. "__hash__() should return a 32-bit integer." 2. "The only required property is that objects which compare equal have the same hash value." 3. "If a class does not define a __cmp__() method it should not define a __hash__() operation either."
3
1465
by: Victor Safronovich | last post by:
please comment this Python 2.2.3 (#42, May 30 2003, 18:12:08) on win32 >>> class A: def __cmp__(self, other): print '%s|%s' %(`self`, `other`) return cmp(self, other) >>> a = A() >>> cmp(a,A()) <__main__.A instance at 0x00989838>|<__main__.A instance at 0x0097D120>
2
1976
by: Alex | last post by:
Entering >>> help(dict) Help on class dict in module __builtin__: class dict(object) | dict() -> new empty dictionary. | dict(mapping) -> new dictionary initialized from a mapping object's | (key, value) pairs. | dict(seq) -> new dictionary initialized as if via:
4
6754
by: JH | last post by:
Hi Can anyone explain to me why the following codes do not work? I want to try out using __cmp__ method to change the sorting order. I subclass the str and override the __cmp__ method so the strings can be sorted by the lengh. I expect the shortest string should be in the front. Thanks >>> class myStr(str): def __init__(self, s): str.__init__(self, s) # Ensure super class is initialized
8
1671
by: insyte | last post by:
I have a class that has, as an attribute, an instance of datetime.datetime(). I would like to be able to compare my class directly to instances of datetime.datetime in addition to other instances of my class. The value used for the comparison in either case should be the value of the datetime attribute of the class: from datetime import datetime class GeneralizedTime(object): def __init__(self, time=None):
17
2713
by: Johannes Bauer | last post by:
Hello group, I'm porting some code of mine to Python 3. One class has the __cmp__ operator overloaded, but comparison doesn't seem to work anymore with that: Traceback (most recent call last): File "./parse", line 25, in <module> print(x < y) TypeError: unorderable types: IP() < IP()
0
7931
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8423
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8411
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8281
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6740
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5885
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
3911
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2437
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1270
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.