473,692 Members | 1,965 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

__cmp__ between dissimilar objects

I have a class that has, as an attribute, an instance of
datetime.dateti me(). I would like to be able to compare my class
directly to instances of datetime.dateti me 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):
if time is None:
self.datetime = datetime.now()
def __cmp__(self, x):
if isinstance(x, GeneralizedTime ):
return cmp(self.dateti me, x.datetime)
if isinstance(x, datetime):
return cmp(self.dateti me, x)

>>import datetime

GeneralizedTi me() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.dateti me to GeneralizedTime

Clearly I'm misunderstandin g something, here. As I understand my code,
I'm directly comparing an instance of datetime (self.datetime) to
another instance of datetime.

What am I failing to grasp?

Thanks!

-Ben

Nov 14 '06 #1
8 1673
At Monday 13/11/2006 21:33, in****@gmail.co m wrote:
>I have a class that has, as an attribute, an instance of
datetime.datet ime(). I would like to be able to compare my class
directly to instances of datetime.dateti me 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):
if time is None:
self.datetime = datetime.now()
def __cmp__(self, x):
if isinstance(x, GeneralizedTime ):
return cmp(self.dateti me, x.datetime)
if isinstance(x, datetime):
return cmp(self.dateti me, x)

>import datetime

GeneralizedTim e() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.dateti me to GeneralizedTime
This appears to be some braindead code in the datetime class.
You have to provide all the "rich-comparison" methods, and even then,
will never work when a datetime instance is at the left of the comparison.

def __lt__(self, other): return self.__cmp__(ot her)<0
def __le__(self, other): return self.__cmp__(ot her)<=0
def __gt__(self, other): return self.__cmp__(ot her)>0
def __ge__(self, other): return self.__cmp__(ot her)>=0
def __eq__(self, other): return self.__cmp__(ot her)==0
def __ne__(self, other): return self.__cmp__(ot her)!=0

When the rich comparison methods raise NotImplementedE rror, the
comparison logic inside the interpreter tries reversing the operands.
But datetime objects don't do that, they raise TypeError, thus
preventing the operand reversing. So any comparison with datetime on
the left and your GeneralizedTime on the right side will fail.
If nobody has an explanation on *why* datetime does this, I'd say it's a bug.
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 14 '06 #2
in****@gmail.co m wrote:
>I have a class that has, as an attribute, an instance of
datetime.dateti me(). I would like to be able to compare my class
directly to instances of datetime.dateti me 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):
if time is None:
self.datetime = datetime.now()
def __cmp__(self, x):
if isinstance(x, GeneralizedTime ):
return cmp(self.dateti me, x.datetime)
if isinstance(x, datetime):
return cmp(self.dateti me, x)
>>>import datetime

GeneralizedT ime() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.dateti me to GeneralizedTime

Clearly I'm misunderstandin g something, here. As I understand my code,
I'm directly comparing an instance of datetime (self.datetime) to
another instance of datetime.
sure looks like you're comparing a datetime instance against a GeneralizeTime
instance to me.

why not just inherit from datetime instead? or read footnote 4 under "supported
operations" on this page for info on how to implement mixed-type comparisions:

http://docs.python.org/lib/datetime-datetime.html

</F>

Nov 14 '06 #3
why not just inherit from datetime instead?

I'll probably do that in the next iteration.
or read footnote 4 under "supported operations" on this page for info on how to
implement mixed-type comparisions:

http://docs.python.org/lib/datetime-datetime.html
OK. I added a 'timetuple' attribute to my class. Now comparisons seem
to "just work". This has made it even more obvious to me that I don't
understand how comparisons function:

If the GeneralizedTime instance is on the LHS of the comparison and the
datetime instance on the RHS, why would datetime's __cmp__ method be
called? I assume its being called since GeneralizedTime sure doesn't
care whether or not it has a timetuple attribute...

I've read through the "Basic customization" section of the language
reference, which doesn't seem to describe a scenario where the __cmp__
method on the RHS is called.

Thanks...

-Ben

Nov 14 '06 #4
When the rich comparison methods raise NotImplementedE rror, the
comparison logic inside the interpreter tries reversing the operands.
Can you point me to a description of this algorithm? It doesn't seem
to be described in the documentation for the rich comparison or __cmp__
methods...

-Ben

Nov 14 '06 #5
At Tuesday 14/11/2006 13:41, in****@gmail.co m wrote:
When the rich comparison methods raise NotImplementedE rror, the
comparison logic inside the interpreter tries reversing the operands.

Can you point me to a description of this algorithm? It doesn't seem
to be described in the documentation for the rich comparison or __cmp__
methods...
PEP 207
http://www.python.org/dev/peps/pep-0207/
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 14 '06 #6
At Tuesday 14/11/2006 09:33, Fredrik Lundh wrote:
>>GeneralizedTi me() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.dateti me to GeneralizedTime

Clearly I'm misunderstandin g something, here. As I understand my code,
I'm directly comparing an instance of datetime (self.datetime) to
another instance of datetime.

sure looks like you're comparing a datetime instance against a GeneralizeTime
instance to me.

why not just inherit from datetime instead? or read footnote 4
under "supported
operations" on this page for info on how to implement mixed-type comparisions:

http://docs.python.org/lib/datetime-datetime.html
Ugh... I hope there were good reasons for doing things so convoluted...
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 14 '06 #7
Can you point me to a description of this algorithm? It doesn't seem
to be described in the documentation for the rich comparison or __cmp__
methods...

PEP 207
http://www.python.org/dev/peps/pep-0207/
So since I implemented __cmp__ instead of the rich comparison
operators, Python first tried to reverse the comparison. This gave
datetime the opportunity to throw TypeError *before* the interpreter
failed over to trying __cmp__.

Is that correct?

Thanks!

-Ben

Nov 14 '06 #8
At Tuesday 14/11/2006 19:27, in****@gmail.co m wrote:
>Can you point me to a description of this algorithm? It doesn't seem
>to be described in the documentation for the rich comparison or __cmp__
>methods...
PEP 207
http://www.python.org/dev/peps/pep-0207/

So since I implemented __cmp__ instead of the rich comparison
operators, Python first tried to reverse the comparison. This gave
datetime the opportunity to throw TypeError *before* the interpreter
failed over to trying __cmp__.

Is that correct?
Exactly. And if datetime were not so special in its implementation, a
NotImplementedE rror (instead of TypeError) would have let your code a
chance of being executed.
--
Gabriel Genellina
Softlab SRL

_______________ _______________ _______________ _____
Correo Yahoo!
Espacio para todos tus mensajes, antivirus y antispam ¡gratis!
¡Abrí tu cuenta ya! - http://correo.yahoo.com.ar
Nov 14 '06 #9

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
2886
by: Lee Harr | last post by:
Let's say I have a class class A: def __init__(self, level): self.level = level and I want to put some of these in a list and sort the list by level a1 = A(1)
31
3907
by: John Roth | last post by:
I'm adding a thread for comments on Gerrit Holl's pre-pep, which can be found here: http://tinyurl.com/2578q Frankly, I like the idea. It's about time that all of the file and directory stuff in the os module got objectified properly (or at least with some semblance of OO propriety!) In the issues section:
3
1467
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>
1
2272
by: Erik Max Francis | last post by:
I've come across a limitation in unpickling certain types of complex data structures which involve instances that override __hash__, and was wondering if it was known (basic searches didn't seem to come up with anything similar) and if there is a workaround for it short of restructuring the data structures in question. The fundamental issue rests with defining classes which override __cmp__ and __hash__ in order to be used as keys in...
39
2800
by: Antoon Pardon | last post by:
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.
17
2721
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
8603
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8538
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
8960
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...
1
8797
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8800
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
7627
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...
0
4323
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...
0
4557
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2237
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.