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):
if time is None:
self.datetime = datetime.now()
def __cmp__(self, x):
if isinstance(x, GeneralizedTime):
return cmp(self.datetime, x.datetime)
if isinstance(x, datetime):
return cmp(self.datetime, x)
>>import datetime
GeneralizedTime() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.datetime to GeneralizedTime
Clearly I'm misunderstanding 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 8 1657
At Monday 13/11/2006 21:33, in****@gmail.com wrote:
>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):
if time is None:
self.datetime = datetime.now()
def __cmp__(self, x):
if isinstance(x, GeneralizedTime):
return cmp(self.datetime, x.datetime)
if isinstance(x, datetime):
return cmp(self.datetime, x)
>import datetime
GeneralizedTime() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ? TypeError: can't compare datetime.datetime 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__(other)<0
def __le__(self, other): return self.__cmp__(other)<=0
def __gt__(self, other): return self.__cmp__(other)>0
def __ge__(self, other): return self.__cmp__(other)>=0
def __eq__(self, other): return self.__cmp__(other)==0
def __ne__(self, other): return self.__cmp__(other)!=0
When the rich comparison methods raise NotImplementedError, 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 in****@gmail.com wrote:
>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):
if time is None:
self.datetime = datetime.now()
def __cmp__(self, x):
if isinstance(x, GeneralizedTime):
return cmp(self.datetime, x.datetime)
if isinstance(x, datetime):
return cmp(self.datetime, x)
>>>import datetime
GeneralizedTime() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.datetime to GeneralizedTime
Clearly I'm misunderstanding 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>
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
When the rich comparison methods raise NotImplementedError, 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
At Tuesday 14/11/2006 13:41, in****@gmail.com wrote:
When the rich comparison methods raise NotImplementedError, 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
At Tuesday 14/11/2006 09:33, Fredrik Lundh wrote:
>>GeneralizedTime() datetime.now()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: can't compare datetime.datetime to GeneralizedTime
Clearly I'm misunderstanding 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
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
At Tuesday 14/11/2006 19:27, in****@gmail.com 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
NotImplementedError (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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
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...
|
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)
|
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...
|
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()
>>>...
|
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...
|
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...
|
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):...
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
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...
|
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,...
|
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...
|
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...
|
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...
|
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,...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
| |