Skip to content

Make PyComplex_RealAsDouble/ImagAsDouble use __complex__ #109598

Closed
@skirpichev

Description

@skirpichev

The C-API docs says: "Return the real/imag part of op as a C double." But the real code looks like:

PyComplex_RealAsDouble(PyObject *op)
{
    if (PyComplex_Check(op)) {
        return ((PyComplexObject *)op)->cval.real;
    }
    else {
        return PyFloat_AsDouble(op);
    }
}

So, we assume instead that the op is a float-like class (a subtype of or something with a __float__ dunder method). Instead, we should look on the __complex__ method in the else branch. This is an issue like #44670, I think.

Minor issue: these functions aren't tested, only indirectly with format() (that will not trigger all possible cases).

Edit:
The current PyComplex_ImagAsDouble() silently returns 0.0 for all non-PyComplexObject objects (or subtypes of). I think it's a bug and we should return -1.0 instead and set the error indicator.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)type-bugAn unexpected behavior, bug, or error

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions