Skip to content

Commit 456e274

Browse files
authored
gh-112451: Prohibit subclassing of datetime.timezone. (#114190)
This is consistent with C-extension datetime.timezone.
1 parent b69548a commit 456e274

File tree

3 files changed

+9
-0
lines changed

3 files changed

+9
-0
lines changed

Lib/_pydatetime.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2347,6 +2347,9 @@ def __new__(cls, offset, name=_Omitted):
23472347
"timedelta(hours=24).")
23482348
return cls._create(offset, name)
23492349

2350+
def __init_subclass__(cls):
2351+
raise TypeError("type 'datetime.timezone' is not an acceptable base type")
2352+
23502353
@classmethod
23512354
def _create(cls, offset, name=None):
23522355
self = tzinfo.__new__(cls)

Lib/test/datetimetester.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,10 @@ def test_inheritance(self):
301301
self.assertIsInstance(timezone.utc, tzinfo)
302302
self.assertIsInstance(self.EST, tzinfo)
303303

304+
def test_cannot_subclass(self):
305+
with self.assertRaises(TypeError):
306+
class MyTimezone(timezone): pass
307+
304308
def test_utcoffset(self):
305309
dummy = self.DT
306310
for h in [0, 1.5, 12]:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Prohibit subclassing pure-Python :class:`datetime.timezone`. This is consistent
2+
with C-extension implementation. Patch by Mariusz Felisiak.

0 commit comments

Comments
 (0)