Skip to content

Commit

Permalink
pythongh-112451: Prohibit subclassing of datetime.timezone. (python#1…
Browse files Browse the repository at this point in the history
…14190)

This is consistent with C-extension datetime.timezone.
  • Loading branch information
felixxm authored and aisk committed Feb 11, 2024
1 parent 3a7ecb0 commit b339012
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Lib/_pydatetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 4 additions & 0 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Prohibit subclassing pure-Python :class:`datetime.timezone`. This is consistent
with C-extension implementation. Patch by Mariusz Felisiak.

0 comments on commit b339012

Please sign in to comment.