Skip to content

Commit 8da9920

Browse files
bombs-kimsobolevnZeroIntensity
authoredNov 19, 2024··
gh-126947: Typechecking for _pydatetime.timedelta.__new__ arguments (#126949)
Co-authored-by: sobolevn <[email protected]> Co-authored-by: Peter Bierma <[email protected]>
1 parent 88dc84b commit 8da9920

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed
 

‎Lib/_pydatetime.py

+13-1
Original file line numberDiff line numberDiff line change
@@ -651,7 +651,19 @@ def __new__(cls, days=0, seconds=0, microseconds=0,
651651
# guide the C implementation; it's way more convoluted than speed-
652652
# ignoring auto-overflow-to-long idiomatic Python could be.
653653

654-
# XXX Check that all inputs are ints or floats.
654+
for name, value in (
655+
("days", days),
656+
("seconds", seconds),
657+
("microseconds", microseconds),
658+
("milliseconds", milliseconds),
659+
("minutes", minutes),
660+
("hours", hours),
661+
("weeks", weeks)
662+
):
663+
if not isinstance(value, (int, float)):
664+
raise TypeError(
665+
f"unsupported type for timedelta {name} component: {type(value).__name__}"
666+
)
655667

656668
# Final values, all integer.
657669
# s and us fit in 32-bit signed ints; d isn't bounded.

‎Lib/test/datetimetester.py

+10
Original file line numberDiff line numberDiff line change
@@ -510,6 +510,7 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
510510

511511
def test_constructor(self):
512512
eq = self.assertEqual
513+
ra = self.assertRaises
513514
td = timedelta
514515

515516
# Check keyword args to constructor
@@ -533,6 +534,15 @@ def test_constructor(self):
533534
eq(td(seconds=0.001), td(milliseconds=1))
534535
eq(td(milliseconds=0.001), td(microseconds=1))
535536

537+
# Check type of args to constructor
538+
ra(TypeError, lambda: td(weeks='1'))
539+
ra(TypeError, lambda: td(days='1'))
540+
ra(TypeError, lambda: td(hours='1'))
541+
ra(TypeError, lambda: td(minutes='1'))
542+
ra(TypeError, lambda: td(seconds='1'))
543+
ra(TypeError, lambda: td(milliseconds='1'))
544+
ra(TypeError, lambda: td(microseconds='1'))
545+
536546
def test_computations(self):
537547
eq = self.assertEqual
538548
td = timedelta
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Raise :exc:`TypeError` in :meth:`!_pydatetime.timedelta.__new__` if the passed arguments are not :class:`int` or :class:`float`, so that the Python
2+
implementation is in line with the C implementation.

0 commit comments

Comments
 (0)
Please sign in to comment.