diff --git a/Lib/_pydatetime.py b/Lib/_pydatetime.py index bca2acf1fc88cf9..83d10aa1bd3397b 100644 --- a/Lib/_pydatetime.py +++ b/Lib/_pydatetime.py @@ -2347,6 +2347,18 @@ def __new__(cls, offset, name=_Omitted): "timedelta(hours=24).") return cls._create(offset, name) + def __init_subclass__(cls): + # When deprecation ends replace with: + # raise TypeError("type 'datetime.timezone' is not an acceptable base type") + import warnings + warnings.warn( + "Subclassing 'datetime.timezone' is deprecated and scheduled for removal " + "in Python 3.15.", + DeprecationWarning, + stacklevel=2, + ) + super().__init_subclass__() + @classmethod def _create(cls, offset, name=None): self = tzinfo.__new__(cls) diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py index 8bda17358db87f9..d4c002dd93a2381 100644 --- a/Lib/test/datetimetester.py +++ b/Lib/test/datetimetester.py @@ -301,6 +301,25 @@ def test_inheritance(self): self.assertIsInstance(timezone.utc, tzinfo) self.assertIsInstance(self.EST, tzinfo) + def test_cannot_subclass_deprecation_warning(self): + if '_Fast' in self.__class__.__name__: + self.skipTest('Only run for Pure Python implementation') + + msg = ( + "Subclassing 'datetime.timezone' is deprecated and scheduled for removal " + "in Python 3.15." + ) + with self.assertWarnsRegex(DeprecationWarning, msg): + class MyTimezone(timezone): pass + + def test_cannot_subclass(self): + if '_Pure' in self.__class__.__name__: + self.skipTest('Only run for Fast C implementation') + + msg = "type 'datetime.timezone' is not an acceptable base type" + with self.assertRaisesRegex(TypeError, msg): + class MyTimezone(timezone): pass + def test_utcoffset(self): dummy = self.DT for h in [0, 1.5, 12]: diff --git a/Misc/NEWS.d/next/Library/2024-01-17-16-34-00.gh-issue-112451.5y9enV.rst b/Misc/NEWS.d/next/Library/2024-01-17-16-34-00.gh-issue-112451.5y9enV.rst new file mode 100644 index 000000000000000..d1b20fd1c2fae61 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2024-01-17-16-34-00.gh-issue-112451.5y9enV.rst @@ -0,0 +1,2 @@ +Deprecate subclassing pure-Python ``datetime.timezone``. +This is consistent with C-extension implementation.