ZetCode

Python __complex__ Method

Last modified November 17, 2026 Python 3.15

The __complex__ method converts an object to a built-in complex number. The complex() constructor calls it, and the result is a new complex value that can be used with all the usual complex operations and with the cmath module. This article explains the conversion protocol, checks what happens with wrong return types, and clears up the common misconception that __complex__ makes objects participate in arithmetic automatically.

How complex() converts an object

The constructor has three forms: two numbers, one string, or one object that implements __complex__. The first two forms build the value from real and imaginary parts or parse text such as "3+4j". The third form calls the hook and returns its result, which must be a complex number.

basic_complex.py
class ComplexPoint:
    def __init__(self, real, imag):
        self.real = real
        self.imag = imag

    def __complex__(self):
        return complex(self.real, self.imag)


p = ComplexPoint(3, 4)

print(complex(3, 4))
print(complex("3+4j"))
print(complex(p))
print(type(complex(p)))
print(p.real, p.imag)

All three calls produce the same value. The object form returns a real complex instance rather than a wrapper, so the caller can use it immediately with abs(), cmath, and the arithmetic operators. The original ComplexPoint is unchanged; the hook only reads its attributes.

$ python basic_complex.py
(3+4j)
(3+4j)
(3+4j)
<class 'complex'>
3 4

Return types and fallbacks

__complex__ must return an actual complex number. Returning a tuple, a float, or any other type raises TypeError with the name of the offending method. When the hook is absent, the constructor falls back to __float__ and then to __index__, producing a complex number with a zero imaginary part.

return_types.py
class BadReturn:
    def __complex__(self):
        return (3, 4)


class FloatOnly:
    def __float__(self):
        return 2.5


class IndexOnly:
    def __index__(self):
        return 7


class Good:
    def __complex__(self):
        return complex(1, -2)


for obj in (BadReturn(), FloatOnly(), IndexOnly(), Good()):
    try:
        print(complex(obj))
    except TypeError as e:
        print(type(e).__name__, e)

The tuple is rejected because it is not a complex number. The two fallback classes succeed, but their imaginary part is zero, which may hide a mistake in a class that was supposed to describe a point in the plane. Define __complex__ explicitly when the conversion has geometric meaning, and let the fallbacks handle purely real values.

$ python return_types.py
TypeError BadReturn.__complex__() must return a complex, not tuple
(2.5+0j)
(7+0j)
(1-2j)

Conversion is not arithmetic

A frequent assumption is that defining __complex__ lets an object take part in expressions with complex numbers. It does not. The binary operators look for __add__, __radd__, and similar methods on the operand types; no numeric conversion is attempted. The object must be converted explicitly, or the class must implement the operator itself.

conversion_not_arithmetic.py
class Force:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __complex__(self):
        return complex(self.x, self.y)

    def __repr__(self):
        return f"Force({self.x}, {self.y})"


class AddableForce(Force):
    def __add__(self, other):
        z = complex(self) + other
        return AddableForce(z.real, z.imag)


f = Force(3, 4)

try:
    print(f + 1j)
except TypeError as e:
    print(type(e).__name__, e)

print(complex(f) + 1j)
print(1j + complex(f))
print(AddableForce(3, 4) + 1j)
print(repr(f))

The plain Force cannot be added to 1j, even though it can be converted to a complex number. Converting first works in both operand orders. AddableForce shows the correct way to support the operator: __add__ performs the conversion itself and returns a new instance. The imaginary literal is a complex, so the sum has float components, and the result prints as Force(3.0, 5.0).

$ python conversion_not_arithmetic.py
TypeError unsupported operand type(s) for +: 'Force' and 'complex'
(3+5j)
(3+5j)
Force(3.0, 5.0)
Force(3, 4)

Polar coordinates

Complex numbers can be stored as a magnitude and an angle instead of real and imaginary parts. cmath.rect() converts polar coordinates to a complex number, and cmath.polar() and cmath.phase() convert back. This is a natural use of __complex__, because the class keeps its own representation and exposes a standard value on demand.

polar.py
import cmath


class Polar:
    def __init__(self, magnitude, angle):
        self.magnitude = magnitude
        self.angle = angle

    def __complex__(self):
        return cmath.rect(self.magnitude, self.angle)


p = Polar(5, 0.9272952180016122)
z = complex(p)

print(f"{z.real:.3f}{z.imag:+.3f}j")
print(cmath.polar(z))
print(cmath.phase(z))
print(abs(z))

The angle is measured in radians, so 0.9272952180016122 corresponds to about 53.13 degrees. The formatted line rounds the rectangular form to 3.000+4.000j. cmath.polar() returns the magnitude and angle as a tuple, and abs() returns the magnitude alone. Note that the round trip can differ in the last digits because of floating-point arithmetic.

$ python polar.py
3.000+4.000j
(5.0, 0.9272952180016121)
0.9272952180016121
5.0

Complex functions from cmath

The cmath module mirrors most of math but returns complex results. Square roots of negative numbers, logarithms of negative numbers, and trigonometric functions of imaginary arguments all produce values with a nonzero imaginary part, which plain math cannot represent.

cmath_ops.py
import cmath

print(cmath.sqrt(-4))
print(cmath.log(-1))
print(cmath.exp(1j * cmath.pi))
print(cmath.sin(1j))

cmath.sqrt(-4) is 2j, and cmath.log(-1) is iπ. Euler's identity appears in the third line as -1 plus a tiny imaginary residue, which is the expected result of exp(iπ) in binary floating point. The last line shows that sin(i) is purely imaginary. These functions accept integers, floats, and complex values, so a class with __complex__ can be converted once and passed to any of them.

$ python cmath_ops.py
2j
3.141592653589793j
(-1+1.2246467991473532e-16j)
1.1752011936438014j

Combining __complex__ with the numeric protocol

A well-behaved numeric type implements several hooks together. The following Vector class converts to complex, computes its length with abs(), supports addition and scalar multiplication, and compares by value. Each operation works on the object's own fields; only __complex__ builds a complex number.

vector.py
import math


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __complex__(self):
        return complex(self.x, self.y)

    def __abs__(self):
        return math.hypot(self.x, self.y)

    def __add__(self, other):
        if isinstance(other, Vector):
            return Vector(self.x + other.x, self.y + other.y)
        return NotImplemented

    def __mul__(self, scalar):
        if isinstance(scalar, (int, float)):
            return Vector(self.x * scalar, self.y * scalar)
        return NotImplemented

    __rmul__ = __mul__

    def __eq__(self, other):
        if isinstance(other, Vector):
            return (self.x, self.y) == (other.x, other.y)
        return NotImplemented

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"


v = Vector(3, 4)
w = Vector(1, 2)

print(complex(v))
print(abs(v))
print(v + w)
print(2 * v)
print(v == Vector(3, 4))
print(v)

complex(v) gives 3+4j, and abs(v) gives the length 5.0 through math.hypot(), which avoids the square root of a sum of squares written by hand. Addition and multiplication return new vectors, and 2 * v reaches __rmul__ because the left operand is an integer. The equality method compares the coordinates, and the representation makes the printed results readable.

$ python vector.py
(3+4j)
5.0
Vector(4, 6)
Vector(6, 8)
True
Vector(3, 4)

Best practices

Keep conversions and arithmetic separate, and make the contract visible:

Source

object.__complex__ - Python documentation

complex() - Python documentation

cmath - Python documentation

Numeric types - Python documentation

In this article we have implemented the __complex__ method. We have covered the constructor forms, the required return type, fallbacks to __float__ and __index__, the difference between conversion and arithmetic, polar coordinates, the cmath module, and a complete numeric protocol for a vector class. For related topics, see Python complex built-in, Python __float__ method, Python __int__ method, and Python __abs__ method.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Python tutorials.