473,383 Members | 1,859 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,383 software developers and data experts.

More puzzling behavior while subclassing datetime

With assistance from Gabriel and Frederik (and a few old threads in
c.l.p.) I've been making headway on my specialized datetime class. Now
I'm puzzled by behavior I didn't expect while attempting to use some of
the alternate datetime constructors. Specifically, it appears if I
call GeneralizedTime.now() it calls the __new__ method of my class but
treats keyword arguments as if they were positional.

My class:

class GeneralizedTime(datetime):
def __new__(cls, time=None, *args, **kwargs):
print time, args, kwargs
if isinstance(time, str):
timeValues, tzOffset = cls.stringToTimeTuple(time)
return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset),
**timeValues)
elif isinstance(time, datetime):
timeValues = time.timetuple()[:6]
tzOffset = time.utcoffset()
return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(time)
@staticmethod
def stringToTimeTuple(timeString):
... regex that parses timeString ...
>>GeneralizedTime.today()
2006 (11, 16, 0, 35, 18, 747275, None) {}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "gentime.py", line 106, in __new__
raise InvalidTime(time)
gentime.InvalidTime: 2006

So it appears the time tuple is being passed to
GeneralizedTime.__new__, but the first value is being assigned to the
"time" argument.

Is this a side effect of how datetime is implemented? Or am I doing
something screwy?

Thanks!

-Ben

Nov 16 '06 #1
3 1349

in****@gmail.com wrote:
With assistance from Gabriel and Frederik (and a few old threads in
c.l.p.) I've been making headway on my specialized datetime class. Now
I'm puzzled by behavior I didn't expect while attempting to use some of
the alternate datetime constructors. Specifically, it appears if I
call GeneralizedTime.now() it calls the __new__ method of my class but
treats keyword arguments as if they were positional.

My class:

class GeneralizedTime(datetime):
def __new__(cls, time=None, *args, **kwargs):
datetime.datetime() takes these arguments: year, month, day[, hour[,
minute[, second[, microsecond[, tzinfo]]]]]), see
http://docs.python.org/lib/datetime-datetime.html
print time, args, kwargs
if isinstance(time, str):
timeValues, tzOffset = cls.stringToTimeTuple(time)
return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset),
**timeValues)
elif isinstance(time, datetime):
timeValues = time.timetuple()[:6]
time.timetuple() does not exist, see
http://docs.python.org/lib/module-time.html, time is represented as a
tuple. checkout time.mktime() on how to convert to a tuple to a time
tzOffset = time.utcoffset()
return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(time)
@staticmethod
def stringToTimeTuple(timeString):
... regex that parses timeString ...
>GeneralizedTime.today()
2006 (11, 16, 0, 35, 18, 747275, None) {}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "gentime.py", line 106, in __new__
raise InvalidTime(time)
gentime.InvalidTime: 2006

So it appears the time tuple is being passed to
GeneralizedTime.__new__, but the first value is being assigned to the
"time" argument.

Is this a side effect of how datetime is implemented? Or am I doing
something screwy?

Thanks!

-Ben
A very cutback part of your code gets the basics working:
from datetime import datetime
class Invalidtime(Exception):
pass

class GeneralizedTime(datetime):
def __new__(cls, *args, **kwargs):
if isinstance(args, tuple):
return datetime.__new__(cls, *args)
else:
raise Invalidtime(args)

t = GeneralizedTime.today()
print t.year
print t.month
print t.day
print t.hour
print t.minute
print t.second
print t.microsecond
print t.tzinfo

Nov 16 '06 #2
in****@gmail.com wrote:
With assistance from Gabriel and Frederik (and a few old threads in
c.l.p.) I've been making headway on my specialized datetime class. Now
I'm puzzled by behavior I didn't expect while attempting to use some of
the alternate datetime constructors. Specifically, it appears if I
call GeneralizedTime.now() it calls the __new__ method of my class but
treats keyword arguments as if they were positional.

My class:

class GeneralizedTime(datetime):
def __new__(cls, time=None, *args, **kwargs):
print time, args, kwargs
if isinstance(time, str):
timeValues, tzOffset = cls.stringToTimeTuple(time)
return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset),
**timeValues)
elif isinstance(time, datetime):
timeValues = time.timetuple()[:6]
tzOffset = time.utcoffset()
return datetime.__new__(cls, tzinfo=GenericTZ(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(time)
@staticmethod
def stringToTimeTuple(timeString):
... regex that parses timeString ...
>>>GeneralizedTime.today()
2006 (11, 16, 0, 35, 18, 747275, None) {}
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "gentime.py", line 106, in __new__
raise InvalidTime(time)
gentime.InvalidTime: 2006

So it appears the time tuple is being passed to
GeneralizedTime.__new__, but the first value is being assigned to the
"time" argument.

Is this a side effect of how datetime is implemented?
Yes. Consider:
>>def today(time=None, *args):
.... print "time = ", time, "args = ", args
....
>>today(2006, 11, 16)
time = 2006 args = (11, 16)

To fix the issue you'll probably have to remove the time=None parameter from
GeneralizedTime.__new__() and instead extract it from args or kwargs.

Peter

Nov 16 '06 #3
Yes. Consider:
>
>def today(time=None, *args):
... print "time = ", time, "args = ", args
...
>today(2006, 11, 16)
time = 2006 args = (11, 16)

To fix the issue you'll probably have to remove the time=None parameter from
GeneralizedTime.__new__() and instead extract it from args or kwargs.
D'oh. That *should* have been obvious.

I am now no longer allowed to program after midnight.

Thanks!

-Ben

Nov 16 '06 #4

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

Similar topics

2
by: BJörn Lindqvist | last post by:
A problem I have occured recently is that I want to subclass builtin types. Especially subclassing list is very troublesome to me. But I can't find the right syntax to use. Take for example this...
1
by: Christopher P. Winter | last post by:
I'm seeing some unexpected behavior with Text-indent, as shown on this page: http://www.chris-winter.com/Digressions/HP_Kayak/My_Kayak.html I set up the following style rules for footnotes: ...
4
by: Sahil Malik [MVP] | last post by:
Okay so lets say I have a valuetype - lets say DateTime. Look at this code . List<DateTime> dt = new List<DateTime>() ; dt.Add(new dateTime(1999,12,1)) dt.AddDays(1) ; <--- This statement...
17
by: ToddLMorgan | last post by:
I'm just starting out with python, after having a long history with Java. I was wondering if there were any resources or tips from anyone out there in Python-land that can help me make the...
2
by: Paulo da Silva | last post by:
Hi! What's wrong with this way of subclassing? from datetime import date class MyDate(date): def __init__(self,year,month=None,day=None): if type(year) is str: # The whole date is here as...
1
by: Mike Rooney | last post by:
Hi everyone, this is my first post to this list. I am trying to create a subclass of datetime.date and pickle it, but I get errors on loading it back. I have created a VERY simple demo of this: ...
73
by: Rajeet Dalawal | last post by:
Good day group. I was asked in an interview to explain the behavior of this program. void main() { char *s = "abc"; int *i = (int *) s; printf("%x", *i); }
1
by: Christian Heimes | last post by:
Rick King schrieb: datetime.date is a C extension class. Subclassing of extension classes may not always work as you'd expect it. Christian
13
by: =?Utf-8?B?QmV0aA==?= | last post by:
Hello. I'm trying to figure out how to create subclasses with properties specific to the subclass and so far it isn't going well. Right now I have a class with an enum representing the type. ...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.