Skip to content

complex(x) ignores an overridden __float__ of a float subclass since 3.14 #161926

Description

@jseop-lim

Bug report

Bug description

Since 3.14, the single-argument form complex(x) no longer calls x.__float__() when x is an instance of a float subclass that overrides __float__. The two-argument form, the keyword form and float(x) still call it, and 3.13 called it in every form.

class F(float):
    def __float__(self):
        return 42.0

x = F(1.0)
print(complex(x))        # 3.13: (42+0j)   3.14+: (1+0j)
print(complex(x, 0))     # (42+0j) on every version
print(complex(real=x))   # (42+0j) on every version
print(float(x))          # 42.0 on every version
3.12.13 3.13.18 3.14.10 3.15.2 3.16.0a2
complex(x) (42+0j) (42+0j) (1+0j) (1+0j) (1+0j)
complex(x, 0) (42+0j) (42+0j) (42+0j) (42+0j) (42+0j)
float(x) 42.0 42.0 42.0 42.0 42.0

Because __float__ is no longer called, an exception it raises no longer propagates either: with def __float__(self): raise Exception, complex(x) raises on 3.13 and returns (1+0j) on 3.14.

The documentation describes the single-argument form of complex() in the same words it uses for float(): "For a general Python object x, complex(x) delegates to x.__complex__(). If __complex__ is not defined then it falls back to __float__." float(x) calls the override, and complex(x) did too up to 3.13.

The new result is the one complex.from_number(x) and float.from_number(x) give. Those, like math.sqrt() and other C-level conversions, read the stored value of a float instance through PyFloat_AsDouble() and have never consulted the override. This report is only about the constructor, whose forms now disagree with each other and with float(x).

Cause

GH-119620 (gh-109218, ef01e95, first released in 3.14.0a1) split the constructor and added a single-argument path, actual_complex_new() in Objects/complexobject.c. That path converts a real argument with PyFloat_AsDouble(arg), which returns the value of any float instance directly (PyFloat_Check) without calling nb_float:

else if ((nbr = Py_TYPE(arg)->tp_as_number) != NULL &&
(nbr->nb_float != NULL || nbr->nb_index != NULL))
{
/* The argument really is entirely real, and contributes
nothing in the imaginary direction.
Just treat it as a double. */
double r = PyFloat_AsDouble(arg);
if (r != -1.0 || !PyErr_Occurred()) {
res = complex_subtype_from_doubles(type, r, 0);
}

The two-argument path in complex_new_impl() keeps PyNumber_Float(r), which 3.13 used for every form and which calls nb_float unless the argument is an exact float:

tmp = PyNumber_Float(r);

The change is not mentioned in What's New in 3.14 or in the NEWS entry of gh-109218, and test_complex exercises __float__ only on a class that does not inherit from float (WithFloat), so no test covers a float subclass that overrides it.

Possible fix

Convert through PyNumber_Float() in the single-argument path as the two-argument path does, or, if the new behavior is intended, document that complex(x) does not consult __float__ of a float subclass.

CPython versions tested on:

3.14, 3.15, 3.16

Operating systems tested on:

Linux

Linked PRs

Activity

  1. added
    type-bug
    on Nov 13, 2026
  2. added
    interpreter-core
    3.14
    3.15
    3.16
    on Nov 13, 2026
  3. skirpichev commented on Nov 13, 2026

    @skirpichev
    Member

    That seems related to #109311, i.e.: can we silently get value of the base type for numeric types of the stdlib?

    If we can, probably new behavior is more appropriate. But as you correctly noted, float() constructor is inconsistent with that. If not, probably it's a valid issue.

    As pointed out in the pr thread:

    With this PR PyComplex_AsCComplex is unchanged, so cmath.sqrt(FloatSub()) will ignore the override. Also note that PyFloat_AsDouble (https://docs.python.org/3/c-api/float.html#c.PyFloat_AsDouble) has the same behavior: for subclasses of float, the __float__ is not called.

    Same happens for math.sqrt(FloatSub()). I don't see good reasons to keep this inconsistency wrt complex/float constructors.

    I also don't see good reasons to override __float__/__complex__ dunders in subclasses. (Any practical example appreciated.) Processing them will only introduce slowdown for handling subclasses. So, my suggestion is that we should align behavior of constructors wrt PyFloat_AsDouble/PyComplex_AsCComplex/etc. Those functions already have correct docs, for example (PyFloat_AsDouble):

    Return a C double representation of the contents of pyfloat. If pyfloat is not a Python floating-point object but has a __float__() method, this method will first be called to convert pyfloat into a float. If __float__() is not defined then it falls back to __index__(). This method returns -1.0 upon failure, so one should call PyErr_Occurred() to check for errors.

    CC @serhiy-storchaka

  4. jseop-lim commented on Nov 17, 2026

    @jseop-lim
    Author

    I found this through differential testing rather than in real code, so I don't have a practical use case for overriding __float__ in a float subclass, and no strong preference on the direction. My concern is only that since 3.14 complex(x) disagrees with complex(x, 0), complex(real=x) and float(x), and that the change came without a What's New entry or a test. Restoring the old behavior, or aligning all of them with PyFloat_AsDouble() and documenting it, would both resolve that.

  5. skirpichev commented on Nov 24, 2026

    @skirpichev
    Member
  6. vstinner commented on Nov 24, 2026

    @vstinner
    Member

    I wrote a short script to see how int(), float() and complex() constructors handle int and float subclasses:

    class CustomInt(int):
        def __int__(self):
            return 5
        def __index__(self):
            return 13
        def __float__(self):
            return 17.0
    
    print(int(CustomInt(123)))  # call CustomInt.__int__()
    print(float(CustomInt(123)))  # call CustomInt.__float__()
    
    class CustomFloat(float):
        def __float__(self):
            return 42.0
    
    print(float(CustomFloat(123.5)))  # call CustomFloat.__float__()
    print(complex(CustomFloat(123.5)))  # DO NOT call CustomFloat.__float__()

    int() and float() do call overridden __int__() and __float__() methods, but complex() doesn't.

    So IMO complex() should be fixed to become inconsistent again (as it was in Python 3.13).

    Note: On Python 3.13, print(complex(CustomFloat(123.5))) does call CustomFloat.__float__() and so is consistent with other constructors.

  7. vstinner commented on Nov 24, 2026

    @vstinner
    Member

    Same happens for math.sqrt(FloatSub()). I don't see good reasons to keep this inconsistency wrt complex/float constructors.

    I don't think that we should change math.sqrt() to call __float__() on float subclasses. Many Objects/floatobject.c functions use CONVERT_TO_DOUBLE() which calls PyFloat_AS_DOUBLE() on float subclasses (do not call __float__()).

    Yeah, Python is not consistent. Some functions call __float__(), some don't. Don't ask me the rule, I don't think that there is a rule for that :-(

    Python do call __int__() on int subclasses. I don't know exactly the rationale for that, but changing that would break the backward compatibility. We should justify such change.

  8. serhiy-storchaka commented on Nov 24, 2026

    @serhiy-storchaka
    Member
  9. added a commit that references this issue on Nov 24, 2026
  10. skirpichev commented on Nov 24, 2026

    @skirpichev
    Member

    So IMO complex() should be fixed to become inconsistent again (as it was in Python 3.13).

    @serhiy-storchaka ?

    IMO, this "regression" has very little practical importance. So, if we are going to do something - lets make change that will have some other benefits, e.g. simplify documentation.

    I don't think that we should change math.sqrt() to call __float__() on float subclasses.

    Then maybe we shouldn't call __float__() on float subclasses in the constructor as well? What the point of doing so, except for backward compatibility?

    I don't think that there is a rule for that :-(

    I think it's simple enough: you can grep CPython sources and see that PyNumber_Float actually used only in few places (e.g. in the formatter helper for int's, instead of calling PyLong_AsDouble() directly). For the rest (e.g. argument handling in mathematical functions): it seems that PyFloat_AsDouble()-like logic is used.

    Python do call int() on int subclasses.

    Yes, in the constructor. And __index__().

    But not for math.integer functions, for example: here PyNumber_Index is used, which doesn't call __index__() on subclasses. Same for PyLong_As*() C-API, and so on.

    IMO, documentation rather vague here. Here is the math.integer module:

    These functions accept integers and objects that implement the __index__() method which is used to convert the object to an integer number.

    Here PyLong_AsLong:

    If obj is not an instance of PyLongObject, first call its __index__() method (if present) to convert it to a PyLongObject.

    Are instances of int's subclasses - "instances of PyLongObject" in above sense? I don't think so, if we consider docs of isinstance():

    Return True if the object argument is an instance of the classinfo argument, or of a (direct, indirect, or virtual) subclass thereof.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    3.143.153.16interpreter-coretype-bug

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions