Skip to content

[mypyc] Specialize .real and .imag on complex, float, int and bool - #22099

Open
rheard wants to merge 3 commits into
python:masterfrom
rheard:fix-mypyc-1228
Open

rheard wants to merge 3 commits into
python:masterfrom
rheard:fix-mypyc-1228

Conversation

@rheard

@rheard rheard commented Oct 4, 2026

Copy link
Copy Markdown
Contributor

Fixes mypyc/mypyc#1228

Reading .real or .imag from a value typed as int, float, complex, or a union of them was compiled to a generic attribute lookup, whose result was then unboxed or type-checked again. Native int, bool and float values were even boxed first, only to read back the same value or zero. I ran into this in the same code as #22097.

This specializes these reads when the static type of the receiver is int, float, complex or a union of them, which includes values narrowed by isinstance():

  • On native int, bool and float values, x.real is the value itself (converted to an int for a bool), and x.imag is 0 or 0.0.
  • When the result is a float (receivers typed float, complex or float | complex), new CPyComplex_Real and CPyComplex_Imag primitives read exact complex, float and int objects directly as a C double.
  • When the result can be an int (receivers such as int | float | complex), new CPyNumber_Real and CPyNumber_Imag primitives return exact int and float objects themselves, as int.real and float.real do, and read exact complex objects directly.

Anything else (a subclass that overrides real or imag, a bool in a union, or an object of the wrong type at runtime) uses the same lookup as before, followed by the same unboxing or type check, so results and error messages don't change.

The run tests cover NaN, infinities, -0.0, a value equal to mypyc's float error value (-113.0), small and large ints, bools, subclasses that override the properties, and the error cases.

Microbenchmark results (Python 3.12, ns per value):

  • z.real + z.imag with z: complex: 59.3 -> 6.0
  • the same with ints passed as z: complex: 55.8 -> 7.1
  • x.real + x.imag with x: float: 49.9 -> 6.0
  • x.real + x.imag with x: int: 41.8 -> 9.9
  • x.real and x.imag with x: int | float | complex: 29.6 -> 8.1 with ints, 36.9 -> 13.0 with floats, 46.3 -> 18.8 with complex values (35.0 -> 25.7 when the three alternate)
  • if isinstance(x, (float, complex)): real, imag = x.real, x.imag with x: Any: 93.9 -> 52.7, or 6.6 together with [mypyc] Add isinstance primitives for complex, type, range, slice and memoryview #22097

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

.real and .imag on complex, float, int and bool values compile to generic attribute lookups

1 participant