https://github.com/python/cpython/commit/456e274578dc9863f42ab24d62adc0d8c511b50f
commit: 456e274578dc9863f42ab24d62adc0d8c511b50f
branch: main
author: Mariusz Felisiak <[email protected]>
committer: erlend-aasland <[email protected]>
date: 2024-01-26T09:33:13+01:00
summary:

gh-112451: Prohibit subclassing of datetime.timezone. (#114190)

This is consistent with C-extension datetime.timezone.

files:
A Misc/NEWS.d/next/Library/2024-01-24-20-11-46.gh-issue-112451.7YrG4p.rst
M Lib/_pydatetime.py
M Lib/test/datetimetester.py

diff --git a/Lib/_pydatetime.py b/Lib/_pydatetime.py
index bca2acf1fc88cf..355145387e355b 100644
--- a/Lib/_pydatetime.py
+++ b/Lib/_pydatetime.py
@@ -2347,6 +2347,9 @@ def __new__(cls, offset, name=_Omitted):
                              "timedelta(hours=24).")
         return cls._create(offset, name)
 
+    def __init_subclass__(cls):
+        raise TypeError("type 'datetime.timezone' is not an acceptable base 
type")
+
     @classmethod
     def _create(cls, offset, name=None):
         self = tzinfo.__new__(cls)
diff --git a/Lib/test/datetimetester.py b/Lib/test/datetimetester.py
index 8bda17358db87f..53ad5e57ada017 100644
--- a/Lib/test/datetimetester.py
+++ b/Lib/test/datetimetester.py
@@ -301,6 +301,10 @@ def test_inheritance(self):
         self.assertIsInstance(timezone.utc, tzinfo)
         self.assertIsInstance(self.EST, tzinfo)
 
+    def test_cannot_subclass(self):
+        with self.assertRaises(TypeError):
+            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-24-20-11-46.gh-issue-112451.7YrG4p.rst 
b/Misc/NEWS.d/next/Library/2024-01-24-20-11-46.gh-issue-112451.7YrG4p.rst
new file mode 100644
index 00000000000000..126ca36a3b7cb1
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2024-01-24-20-11-46.gh-issue-112451.7YrG4p.rst
@@ -0,0 +1,2 @@
+Prohibit subclassing pure-Python :class:`datetime.timezone`. This is consistent
+with C-extension implementation. Patch by Mariusz Felisiak.

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-checkins.python.org/
Member address: [email protected]

Reply via email to