Skip to content

[mypyc] Add primitive for abs() of complex - #22459

Open
rheard wants to merge 1 commit into
python:masterfrom
rheard:mypyc-abs-complex
Open

rheard wants to merge 1 commit into
python:masterfrom
rheard:mypyc-abs-complex

Conversation

@rheard

@rheard rheard commented Nov 13, 2026

Copy link
Copy Markdown
Contributor

Browsing the mypyc issues, I saw mypyc/mypyc#1094 closed recently which led to this.

abs() has primitives for float and, since #22363, int, but abs(z) for z: complex used the generic PyNumber_Absolute(). That creates a float object for the result, which is then unboxed right away, since the result type is float.

This adds CPyComplex_Abs(), which is used when the argument is a complex or a union such as float | complex, and the result is a float.

is_builtin_number_type() moves from expression.py to specialize.py, so the .real/.imag code and the new specializer can both use it (expression.py already imports from specialize.py). The test fixture's complex gets an __abs__.

Performance

master this PR
total += abs(z) in a compiled loop 30.1 ns 8.1 ns 3.7x
sum of abs() over a list of 1000 complex numbers 29.2 ns 7.6 ns 3.8x
abs(z) in a compiled function called from Python 68.1 ns 39.2 ns 1.7x

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.

1 participant