Message 308961 - Python tracker (original) (raw)

When preparing some tests for how subclasses of date and datetime react as part of a fix for issue 32403, I noticed a fairly big example of where subclass is not preserved - tzinfo.fromutc:

from datetime import datetime, timezone

class DateTimeSubclass(datetime):
    pass

dt = DateTimeSubclass(2012, 1, 1)
dt2 = dt.astimezone(timezone.utc)

print(type(dt))
print(type(dt2))

# Result:
# <class '__main__.DateTimeSubclass'>
# <class 'datetime.datetime'>

This also affects datetime.fromtimestamp and datetime.now, since both of these, when passed a time zone argument, will call fromutc internally. I personally think that Python's tzinfo.fromutc should preserve the object's class, but this is counter to the current API.

And either way, it's quite inconsistent to have DateTimeSubclass.now() return DateTimeSubclass but have DateTimeSubclass.now(timezone.utc) return datetime.datetime.

There is probably a somewhat inelegant way to get the alternate constructors working properly (ignore the type of the argument up until the last return and then construct the subclass from the components of the datetime), but I think it might be better to fix the behavior of tzinfo.fromutc.

Somewhat related to issue 32404 and 31222, in that this concerns which operations preserve type in subclasses.