[New-bugs-announce] [issue32794] PyNumber_Float counterpart that doesn't accept strings

Mark Dickinson report at bugs.python.org
Thu Feb 8 04:07:52 EST 2018


New submission from Mark Dickinson <dickinsm at gmail.com>:

Our abstract objects layer in the C-API includes PyNumber_Float [1], which is equivalent to a Python-level `float` call, including the behaviour of accepting strings. I'm not convinced that it's a particularly useful function: I suspect that it's more common to need to either convert a string to a float, or to convert a float-y object (i.e., something whose type implements __float__) to a float, but not both at once. The second need is precisely the one that most of the math module has: accept anything that implements __float__, but don't accept strings.

Yesterday I found myself writing the following code for a 3rd-party extension module:


static PyObject *
_validate_float(PyObject *value) {
    double value_as_double;

    /* Fast path: avoid creating a new object if it's not necessary. */
    if (PyFloat_CheckExact(value)) {
        Py_INCREF(value);
        return value;
    }

    value_as_double = PyFloat_AsDouble(value);
    if (value_as_double == -1.0 && PyErr_Occurred()) {
        return NULL;
    }
    return PyFloat_FromDouble(value_as_double);
}


Would it be worth adding a new C-API level function that does essentially the above? The semantics of such a function seem clear cut. The major problem would be figuring out what to call it, since to me PyNumber_Float is the one obvious name for such behaviour, but it's already taken. :-)

Please note that I'm not suggesting removing / deprecating / changing the existing PyNumber_Float. That would amount to gratuitous breakage.


[1] https://docs.python.org/3.6/c-api/number.html#c.PyNumber_Float

----------
components: Interpreter Core
messages: 311819
nosy: mark.dickinson
priority: normal
severity: normal
status: open
title: PyNumber_Float counterpart that doesn't accept strings
type: enhancement
versions: Python 3.8

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue32794>
_______________________________________


More information about the New-bugs-announce mailing list