Skip to content

Commit

Permalink
pythongh-112451: Prohibit subclassing of datetime.timezone.
Browse files Browse the repository at this point in the history
This is consistent with C-extension datetime.timezone.
  • Loading branch information
felixxm committed Jan 17, 2024
1 parent 8cf37f2 commit 0820caa
Show file tree
Hide file tree
Showing 3 changed files with 10 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
5 changes: 5 additions & 0 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,6 +301,11 @@ def test_inheritance(self):
self.assertIsInstance(timezone.utc, tzinfo)
self.assertIsInstance(self.EST, tzinfo)

def test_cannot_subclass(self):
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]:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Prohibit subclassing pure-Python ``datetime.timezone``.
This is consistent with C-extension implementation.

0 comments on commit 0820caa

Please sign in to comment.