This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author p-ganssle
Recipients belopolsky, p-ganssle
Date 2017-12-23.18:15:39
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1514052939.19.0.213398074469.issue32417@psf.upfronthosting.co.za>
In-reply-to
Content
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.
History
Date User Action Args
2017-12-23 18:15:39p-gansslesetrecipients: + p-ganssle, belopolsky
2017-12-23 18:15:39p-gansslesetmessageid: <1514052939.19.0.213398074469.issue32417@psf.upfronthosting.co.za>
2017-12-23 18:15:39p-gansslelinkissue32417 messages
2017-12-23 18:15:39p-gansslecreate