This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Author mark.dickinson
Recipients mark.dickinson
Date 2018-02-08.09:07:52
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1518080872.68.0.467229070634.issue32794@psf.upfronthosting.co.za>
In-reply-to
Content
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
History
Date User Action Args
2018-02-08 09:07:52mark.dickinsonsetrecipients: + mark.dickinson
2018-02-08 09:07:52mark.dickinsonsetmessageid: <1518080872.68.0.467229070634.issue32794@psf.upfronthosting.co.za>
2018-02-08 09:07:52mark.dickinsonlinkissue32794 messages
2018-02-08 09:07:52mark.dickinsoncreate