So I just tracked down a strange bug in my Python program which was caused by that fact that I mixed up arguments to a function and mistakenly passed True
to time.sleep()
. Python seems to silently convert True
to 1
The docs say:
Suspend execution for the given number of seconds. The argument may be a floating point number ...
In general, Python is happy to throw exceptions when input does not match the expected type or range. Why does sleep
silently convert True
to a number?
In python, Bool
is a subclass of int
>>> issubclass(bool, int)
True
Here's the source from svn: http://svn.python.org/projects/python/trunk/Modules/timemodule.c
PyArg_ParseTuple
converts the arg to a float
with the d:
specifier
static PyObject *
time_sleep(PyObject *self, PyObject *args)
{
double secs;
if (!PyArg_ParseTuple(args, "d:sleep", &secs))
return NULL;
if (floatsleep(secs) != 0)
return NULL;
Py_INCREF(Py_None);
return Py_None;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.