[New-bugs-announce] [issue20371] datetime.datetime.replace bypasses a subclass's __new__

Andrew Lutomirski report at bugs.python.org
Thu Jan 23 20:47:24 CET 2014

New submission from Andrew Lutomirski:

I'll admit that what I'm doing is possibly unhealthy.  Nonetheless, I find this behavior *extremely* surprising.  This code:

--- start code ---

import datetime

class my_dt(datetime.datetime):
    def __new__(cls, *args, **kwargs):
        print('In my_dt.__new__')
        return datetime.datetime.__new__(cls, *args, **kwargs)

    def __init__(self, *args, **kwargs):
        print('In my_dt.__init__')
        super(my_dt, self).__init__()

dt = datetime.datetime.now()

print('Create a my_dt')
t = my_dt(dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo)

print('Calling replace')
t2 = t.replace(tzinfo=None)
print('Got a %r' % type(t2))

--- end code ---

results in:

Create a my_dt
In my_dt.__new__
In my_dt.__init__
Calling replace
Got a <class '__main__.my_dt'>

So datetime.datetime.replace will create an object of type my_dt *without calling __new__ or __init__*.  This should (AFAIK) be impossible.

I think that datetime.datetime.replace should either return an actual datetime object or that it should invoke __new__ and probably __init__.

components: Library (Lib)
messages: 208980
nosy: Andrew.Lutomirski
priority: normal
severity: normal
status: open
title: datetime.datetime.replace bypasses a subclass's __new__
versions: Python 3.3

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list