Skip to content

[mypyc] Add primitive for abs(int) - #22363

Merged
p-sawicki merged 1 commit into
python:masterfrom
hnwg:dev
Nov 4, 2026
Merged

p-sawicki merged 1 commit into
python:masterfrom
hnwg:dev

Conversation

@hnwg

@hnwg hnwg commented Nov 4, 2026

Copy link
Copy Markdown
Contributor

Fixes mypyc/mypyc#1094.

abs() on an int used to box it, go through PyNumber_Absolute and unbox the result. This adds
CPyTagged_Absolute, modeled on CPyTagged_Negate: short ints are handled inline, and long ints
fall back to PyNumber_Absolute. So does -2**62, since its absolute value doesn't fit in a short int.

A loop summing abs(i) over 2M ints went from 138 ms to 18 ms for me (Python 3.14 on Windows,
median of 9 runs).

@p-sawicki p-sawicki left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

looks good, thanks!

@p-sawicki
p-sawicki merged commit 1231cf1 into python:master Nov 4, 2026
19 checks passed
@Jahongir-Qurbonov Jahongir-Qurbonov mentioned this pull request Nov 10, 2026
13 of 14 tasks
JukkaL pushed a commit that referenced this pull request Nov 16, 2026
Follow-up to #22363.

`abs()` on a native int type failed to type check (`Argument 1 to "abs"
has incompatible type "i64"`), because the native int classes in mypy's
own `mypy_extensions` stubs define `__neg__`, `__pos__` and `__invert__`
but not `__abs__`. This adds it for all eight types (`i8`, `i16`, `i32`,
`i64`, `u8`, `u16`, `u32`, `u64`) to the bundled stubs and to the test
stubs. The new asserts in the `run-*.test` files fail to type check on
master.

mypyc compiles the call with the `abs(int)` primitive from #22363: the
value is converted to a tagged int, passed to `CPyTagged_Absolute`, and
converted back. Only `i64` and `u64` values that don't fit in a short
tagged int fall back to `PyNumber_Absolute`.
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.

Add primitive for abs(integer)

2 participants