0
0
mirror of https://github.com/python/cpython.git synced 2024-11-24 00:38:00 +01:00

gh-126947: Typechecking for _pydatetime.timedelta.__new__ arguments (#126949)

Co-authored-by: sobolevn <mail@sobolevn.me>
Co-authored-by: Peter Bierma <zintensitydev@gmail.com>
This commit is contained in:
Beomsoo Kim 2024-11-20 04:40:52 +09:00 committed by GitHub
parent 88dc84bcf9
commit 8da9920a80
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 25 additions and 1 deletions

View File

@ -651,7 +651,19 @@ class timedelta:
# guide the C implementation; it's way more convoluted than speed-
# ignoring auto-overflow-to-long idiomatic Python could be.
# XXX Check that all inputs are ints or floats.
for name, value in (
("days", days),
("seconds", seconds),
("microseconds", microseconds),
("milliseconds", milliseconds),
("minutes", minutes),
("hours", hours),
("weeks", weeks)
):
if not isinstance(value, (int, float)):
raise TypeError(
f"unsupported type for timedelta {name} component: {type(value).__name__}"
)
# Final values, all integer.
# s and us fit in 32-bit signed ints; d isn't bounded.

View File

@ -510,6 +510,7 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
def test_constructor(self):
eq = self.assertEqual
ra = self.assertRaises
td = timedelta
# Check keyword args to constructor
@ -533,6 +534,15 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
eq(td(seconds=0.001), td(milliseconds=1))
eq(td(milliseconds=0.001), td(microseconds=1))
# Check type of args to constructor
ra(TypeError, lambda: td(weeks='1'))
ra(TypeError, lambda: td(days='1'))
ra(TypeError, lambda: td(hours='1'))
ra(TypeError, lambda: td(minutes='1'))
ra(TypeError, lambda: td(seconds='1'))
ra(TypeError, lambda: td(milliseconds='1'))
ra(TypeError, lambda: td(microseconds='1'))
def test_computations(self):
eq = self.assertEqual
td = timedelta

View File

@ -0,0 +1,2 @@
Raise :exc:`TypeError` in :meth:`!_pydatetime.timedelta.__new__` if the passed arguments are not :class:`int` or :class:`float`, so that the Python
implementation is in line with the C implementation.