New submission from Oren Milman:
------------ current state ------------
if (PyNumber_Check(obj)) {
someVar = PyNumber_AsSsize_t(obj, SomeError);
if (someVar == -1 && PyErr_Occurred()) {
return errVal;
}
}
else {
PyErr_Format(PyExc_TypeError,
"integer argument expected, got '%.200s'",
Py_TYPE(obj)->tp_name);
return errVal;
}
Something similar to this happens in:
- Modules/mmapmodule.c in mmap_convert_ssize_t
- Modules/_io/_iomodule.c in _PyIO_ConvertSsize_t
- Modules/_io/stringio.c in:
* _io_StringIO_read_impl
* _io_StringIO_readline_impl
* _io_StringIO_truncate_impl
(Moreover, in:
- Objects/bytes_methods.c in parse_args_finds_byte
- Objects/exceptions.c in oserror_init
PyNumber_AsSsize_t is called only if PyNumber_Check returns true.)
Note that:
- PyNumber_Check checks whether nb_int != NULL or nb_float != NULL.
- PyNumber_AsSsize_t calls PyNumber_Index, which, before calling
nb_index, raises a TypeError (with a similar error message) in case
nb_index == NULL.
- The docs say '... when __index__() is defined __int__() should also be
defined ...'.
So the behavior with and without the call to PyNumber_Check is quite the same.
The only potential advantage of calling PyNumber_Check is skipping the call to
PyNumber_AsSsize_t.
But PyNumber_AsSsize_t would be called also in case
nb_index == NULL and (nb_int != NULL or nb_float != NULL).
Thus, the only case in which the call to PyNumber_Check might be useful, is
when nb_int == nb_float == nb_index == NULL.
------------ proposed changes ------------
Either remove each of these calls to PyNumber_Check, or at least replace it
with a call to PyIndex_Check, which checks whether nb_index != NULL, and thus
would be more useful than PyNumber_Check.
Note that such a change shouldn't affect the behavior, except for a slightly
different wording of the error message in case a TypeError is raised.
----------
components: IO
messages: 289048
nosy: Oren Milman
priority: normal
severity: normal
status: open
title: unoptimal calls to PyNumber_Check
type: enhancement
versions: Python 3.7
_______________________________________
Python tracker <[email protected]>
<http://bugs.python.org/issue29730>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com