From 3fba5e67a6545ac3d86cd4448c26615a7dab5617 Mon Sep 17 00:00:00 2001 From: Chao Peng Date: Fri, 19 Dec 2025 16:29:02 -0500 Subject: [PATCH] support object with __float__ defined in time.sleep --- Lib/test/test_time.py | 32 +++++++++++++++++++ ...5-12-19-16-28-44.gh-issue-79888.ib0rM-.rst | 1 + Python/pytime.c | 11 +++++++ 3 files changed, 44 insertions(+) create mode 100644 Misc/NEWS.d/next/Library/2025-12-19-16-28-44.gh-issue-79888.ib0rM-.rst diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py index c7e81fff6f776b..0ff0c0f5d96a65 100644 --- a/Lib/test/test_time.py +++ b/Lib/test/test_time.py @@ -180,6 +180,38 @@ def test_sleep(self): with self.subTest(value=value): time.sleep(value) + class IndexLike: + def __init__(self, value): + self.value = int(value) + def __index__(self): + return self.value + index_like = IndexLike(1) + + with self.subTest(value = index_like): + self._test_sleep_duration(index_like) + + class FloatLike: + def __init__(self, value): + self.value = float(value) + def __float__(self): + return self.value + float_like = FloatLike(0.5) + + + with self.subTest(value = float_like): + self._test_sleep_duration(float_like) + + def _test_sleep_duration(self, secs): + t1 = time.monotonic() + time.sleep(secs) + t2 = time.monotonic() + dt = t2 - t1 + self.assertGreater(t2, t1) + # bpo-20101: tolerate a difference of 50 ms because of bad timer + # resolution on Windows + self.assertTrue(float(secs) - 0.05 <= dt) + + def test_epoch(self): # bpo-43869: Make sure that Python use the same Epoch on all platforms: # January 1, 1970, 00:00:00 (UTC). diff --git a/Misc/NEWS.d/next/Library/2025-12-19-16-28-44.gh-issue-79888.ib0rM-.rst b/Misc/NEWS.d/next/Library/2025-12-19-16-28-44.gh-issue-79888.ib0rM-.rst new file mode 100644 index 00000000000000..78ba68c3d15efc --- /dev/null +++ b/Misc/NEWS.d/next/Library/2025-12-19-16-28-44.gh-issue-79888.ib0rM-.rst @@ -0,0 +1 @@ +support object with __float__ defined in time.sleep diff --git a/Python/pytime.c b/Python/pytime.c index 2f3d854428b4bf..0155852fc0b278 100644 --- a/Python/pytime.c +++ b/Python/pytime.c @@ -584,6 +584,17 @@ pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round, *tp = ns; return 0; } + else if (PyFloat_Check(obj)) { + double d = PyFloat_AsDouble(obj); + if (d == -1 && PyErr_Occurred()) { + return -1; + } + if (isnan(d)) { + PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)"); + return -1; + } + return pytime_from_double(tp, d, round, unit_to_ns); + } else { double d; d = PyFloat_AsDouble(obj);