473,808 Members | 2,835 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.stringToTim eTuple(time)
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
**timeValues)
elif isinstance(time , datetime):
timeValues = time.timetuple( )[:6]
tzOffset = time.utcoffset( )
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(tim e)
@staticmethod
def stringToTimeTup le(timeString):
... regex that parses timeString ...
>>GeneralizedTi me.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(tim e)
gentime.Invalid Time: 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 1376

in****@gmail.co m 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.dateti me() 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.stringToTim eTuple(time)
return datetime.__new_ _(cls, tzinfo=GenericT Z(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=GenericT Z(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(tim e)
@staticmethod
def stringToTimeTup le(timeString):
... regex that parses timeString ...
>GeneralizedTim e.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(tim e)
gentime.Invalid Time: 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(Exc eption):
pass

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

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.co m 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.stringToTim eTuple(time)
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
**timeValues)
elif isinstance(time , datetime):
timeValues = time.timetuple( )[:6]
tzOffset = time.utcoffset( )
return datetime.__new_ _(cls, tzinfo=GenericT Z(tzOffset),
*timeValues)
elif time is None:
print "Still gotta figure out now to do this one..."
else:
raise Invalidtime(tim e)
@staticmethod
def stringToTimeTup le(timeString):
... regex that parses timeString ...
>>>GeneralizedT ime.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(tim e)
gentime.Invalid Time: 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
5166
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 class which is supposed to be a representation of a genome: class Genome(list): def __init__(self): list.__init__(self) self = ....
1
1859
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: DIV.FootRule { Border-bottom: 1px Solid Gray; Margin-bottom: 2px; Text-align: Left; Width: 20% }
4
1308
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 won't actually change the date time stored in the List<T> dt.
17
2000
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 transition as successfully as possible? Perhaps you've made the transition yourself or just have experience with folks who have made the transition. I'm looking for the common types of mistakes that say a Java/C# or even C++ developer may commonly...
2
1236
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 a string
1
2528
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: import datetime class MyDate(datetime.date): """ This should be pickleable.
73
2839
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
1414
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
1463
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. The class has all the properties specific to all the types, but what I want instead is to move those properties to subclasses specific to each type. I have code like this:
0
9721
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
9600
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
10374
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
10374
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
10114
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
6880
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 then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5686
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4331
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
3
3011
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.