Skip to content

Commit

Permalink
pythongh-112451: Deprecate subclassing of pure-Python 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 7573c44 commit 832d948
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 0 deletions.
12 changes: 12 additions & 0 deletions Lib/_pydatetime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
19 changes: 19 additions & 0 deletions Lib/test/datetimetester.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Deprecate subclassing pure-Python ``datetime.timezone``.
This is consistent with C-extension implementation.

0 comments on commit 832d948

Please sign in to comment.