[New-bugs-announce] [issue32417] fromutc does not respect datetime subclasses
report at bugs.python.org
Sat Dec 23 13:15:39 EST 2017
New submission from Paul Ganssle <p.ganssle at gmail.com>:
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
dt = DateTimeSubclass(2012, 1, 1)
dt2 = dt.astimezone(timezone.utc)
# <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.
nosy: belopolsky, p-ganssle
title: fromutc does not respect datetime subclasses
versions: Python 3.5, Python 3.6, Python 3.7, Python 3.8
Python tracker <report at bugs.python.org>
More information about the New-bugs-announce