Skip to content

Commit cd231e6

Browse files
committed
gh-112451: Deprecate subclassing of pure-Python datetime.timezone.
This is consistent with C-extension datetime.timezone.
1 parent 8cf37f2 commit cd231e6

File tree

3 files changed

+33
-0
lines changed

3 files changed

+33
-0
lines changed

Lib/_pydatetime.py

+12
Original file line numberDiff line numberDiff line change
@@ -2347,6 +2347,18 @@ def __new__(cls, offset, name=_Omitted):
23472347
"timedelta(hours=24).")
23482348
return cls._create(offset, name)
23492349

2350+
def __init_subclass__(cls):
2351+
# When deprecation ends replace with:
2352+
# raise TypeError("type 'datetime.timezone' is not an acceptable base type")
2353+
import warnings
2354+
warnings.warn(
2355+
"Subclassing 'datetime.timezone' is deprecated and scheduled for removal "
2356+
"in Python 3.15.",
2357+
DeprecationWarning,
2358+
stacklevel=2,
2359+
)
2360+
super().__init_subclass__()
2361+
23502362
@classmethod
23512363
def _create(cls, offset, name=None):
23522364
self = tzinfo.__new__(cls)

Lib/test/datetimetester.py

+19
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,25 @@ def test_inheritance(self):
301301
self.assertIsInstance(timezone.utc, tzinfo)
302302
self.assertIsInstance(self.EST, tzinfo)
303303

304+
def test_cannot_subclass_deprecation_warning(self):
305+
if '_Fast' in self.__class__.__name__:
306+
self.skipTest('Only run for Pure Python implementation')
307+
308+
msg = (
309+
"Subclassing 'datetime.timezone' is deprecated and scheduled for removal "
310+
"in Python 3.15."
311+
)
312+
with self.assertWarnsRegex(DeprecationWarning, msg):
313+
class MyTimezone(timezone): pass
314+
315+
def test_cannot_subclass(self):
316+
if '_Pure' in self.__class__.__name__:
317+
self.skipTest('Only run for Fast C implementation')
318+
319+
msg = "type 'datetime.timezone' is not an acceptable base type"
320+
with self.assertRaisesRegex(TypeError, msg):
321+
class MyTimezone(timezone): pass
322+
304323
def test_utcoffset(self):
305324
dummy = self.DT
306325
for h in [0, 1.5, 12]:
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Deprecate subclassing pure-Python ``datetime.timezone``.
2+
This is consistent with C-extension implementation.

0 commit comments

Comments
 (0)