Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions Lib/test/test_time.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,12 @@ def test_sleep_exceptions(self):
self.assertRaises(ValueError, time.sleep, -1)
self.assertRaises(ValueError, time.sleep, -0.1)

# Improved exception #81267
with self.assertRaises(TypeError) as errmsg:
time.sleep([])
self.assertIn("integer or float", str(errmsg.exception))


def test_sleep(self):
for value in [-0.0, 0, 0.0, 1e-100, 1e-9, 1e-6, 1, 1.2]:
with self.subTest(value=value):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Correct :func:`time.sleep` error message when an object that cannot be interpreted
as an integer or float is provided.
3 changes: 2 additions & 1 deletion Modules/timemodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -398,8 +398,9 @@ time_sleep(PyObject *self, PyObject *timeout_obj)
}

PyTime_t timeout;
if (_PyTime_FromSecondsObject(&timeout, timeout_obj, _PyTime_ROUND_TIMEOUT))
if (_PyTime_FromSecondsObject(&timeout, timeout_obj, _PyTime_ROUND_TIMEOUT)) {
return NULL;
}
if (timeout < 0) {
PyErr_SetString(PyExc_ValueError,
"sleep length must be non-negative");
Expand Down
34 changes: 19 additions & 15 deletions Python/pytime.c
Original file line number Diff line number Diff line change
Expand Up @@ -594,26 +594,30 @@ pytime_from_object(PyTime_t *tp, PyObject *obj, _PyTime_round_t round,
}
return pytime_from_double(tp, d, round, unit_to_ns);
}
else {
long long sec = PyLong_AsLongLong(obj);
if (sec == -1 && PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
pytime_overflow();
}
return -1;
}

static_assert(sizeof(long long) <= sizeof(PyTime_t),
"PyTime_t is smaller than long long");
PyTime_t ns = (PyTime_t)sec;
if (pytime_mul(&ns, unit_to_ns) < 0) {
long long sec = PyLong_AsLongLong(obj);
if (sec == -1 && PyErr_Occurred()) {
if (PyErr_ExceptionMatches(PyExc_OverflowError)) {
pytime_overflow();
return -1;
}
if (PyErr_ExceptionMatches(PyExc_TypeError)) {
PyErr_Format(PyExc_TypeError,
"'%T' object cannot be interpreted as an integer or float",
obj);
}
return -1;
}

*tp = ns;
return 0;
static_assert(sizeof(long long) <= sizeof(PyTime_t),
"PyTime_t is smaller than long long");
PyTime_t ns = (PyTime_t)sec;
if (pytime_mul(&ns, unit_to_ns) < 0) {
pytime_overflow();
return -1;
}

*tp = ns;
return 0;
}


Expand Down
Loading