Skip to content

[mypyc] Allow abs() on native int types - #22367

Open
Pixeless001 wants to merge 2 commits into
python:masterfrom
Pixeless001:native-int-abs
Open

Pixeless001 wants to merge 2 commits into
python:masterfrom
Pixeless001:native-int-abs

Conversation

@Pixeless001

@Pixeless001 Pixeless001 commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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.

@github-actions

This comment has been minimized.

@JukkaL JukkaL 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.

This makes abs() work, but it's very slow with native integers since it uses the generic slow path. Since native integers are entirely performance focused, we should instead add a new primitive that gets lowered to efficient IR in the lowering pass instead, so that this would be fast, as is reasonable to expect.

@JukkaL

JukkaL commented Nov 13, 2026

Copy link
Copy Markdown
Collaborator

Ah rebasing on top of #22363 would fix much of the performance issue. This will also need support for the recently added u64, u32, u16 and i8 native integer types. Can you rebase and support the new types as well?

@Pixeless001

Copy link
Copy Markdown
Contributor Author

Rebased, and added __abs__ to i8, u16, u32 and u64. After the rebase the call uses the CPyTagged_Absolute primitive from #22363 with a conversion to and from a tagged int on each side, and PyNumber_Absolute is only reached for i64 and u64 values that don't fit in a short int.

One side effect of converting back is that abs(i8(-128)) raises ValueError where -x would wrap to -128. If you want abs lowered natively for these types instead, I can do it in this PR or in a follow-up.

@github-actions

Copy link
Copy Markdown
Contributor

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

@Pixeless001
Pixeless001 requested a review from JukkaL November 13, 2026 19:20
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.

2 participants