Skip to content

Commit 3fba5e6

Browse files
committed
support object with __float__ defined in time.sleep
1 parent 08bc03f commit 3fba5e6

File tree

3 files changed

+44
-0
lines changed

3 files changed

+44
-0
lines changed

Lib/test/test_time.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -180,6 +180,38 @@ def test_sleep(self):
180180
with self.subTest(value=value):
181181
time.sleep(value)
182182

183+
class IndexLike:
184+
def __init__(self, value):
185+
self.value = int(value)
186+
def __index__(self):
187+
return self.value
188+
index_like = IndexLike(1)
189+
190+
with self.subTest(value = index_like):
191+
self._test_sleep_duration(index_like)
192+
193+
class FloatLike:
194+
def __init__(self, value):
195+
self.value = float(value)
196+
def __float__(self):
197+
return self.value
198+
float_like = FloatLike(0.5)
199+
200+
201+
with self.subTest(value = float_like):
202+
self._test_sleep_duration(float_like)
203+
204+
def _test_sleep_duration(self, secs):
205+
t1 = time.monotonic()
206+
time.sleep(secs)
207+
t2 = time.monotonic()
208+
dt = t2 - t1
209+
self.assertGreater(t2, t1)
210+
# bpo-20101: tolerate a difference of 50 ms because of bad timer
211+
# resolution on Windows
212+
self.assertTrue(float(secs) - 0.05 <= dt)
213+
214+
183215
def test_epoch(self):
184216
# bpo-43869: Make sure that Python use the same Epoch on all platforms:
185217
# January 1, 1970, 00:00:00 (UTC).
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
support object with __float__ defined in time.sleep

Python/pytime.c

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,17 @@ pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
584584
*tp = ns;
585585
return 0;
586586
}
587+
else if (PyFloat_Check(obj)) {
588+
double d = PyFloat_AsDouble(obj);
589+
if (d == -1 && PyErr_Occurred()) {
590+
return -1;
591+
}
592+
if (isnan(d)) {
593+
PyErr_SetString(PyExc_ValueError, "Invalid value NaN (not a number)");
594+
return -1;
595+
}
596+
return pytime_from_double(tp, d, round, unit_to_ns);
597+
}
587598
else {
588599
double d;
589600
d = PyFloat_AsDouble(obj);

0 commit comments

Comments
 (0)