New submission from Paul Ganssle <p.gans...@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 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. ---------- messages: 308961 nosy: belopolsky, p-ganssle priority: normal severity: normal status: open title: fromutc does not respect datetime subclasses versions: Python 3.5, Python 3.6, Python 3.7, Python 3.8 _______________________________________ Python tracker <rep...@bugs.python.org> <https://bugs.python.org/issue32417> _______________________________________ _______________________________________________ Python-bugs-list mailing list Unsubscribe: https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com