Skip to content

[mypyc] Add isinstance primitives for complex, type, range, slice and memoryview - #22097

Merged
JukkaL merged 2 commits into
python:masterfrom
rheard:isinstance-primatives
Oct 5, 2026
Merged

JukkaL merged 2 commits into
python:masterfrom
rheard:isinstance-primatives

Conversation

@rheard

@rheard rheard commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

isinstance(x, complex) wasn't specialized, so every call looked up builtins.complex by name and went through PyObject_IsInstance. Because the tuple fast path from #19949 only applies when every member is a primitive type, isinstance(x, (float, complex)) was worse still: it built a new tuple on every call, and float lost its fast path too. This is an issue I have run into in my personal projects.

This adds isinstance primitives for complex, type, range, slice and memoryview (PyComplex_Check, PyType_Check, etc.), plus direct type object loads for complex, slice and memoryview so things like type(x) is complex don't go through builtins either. Tuples such as (float, complex) and (bytes, bytearray, memoryview) now use the existing chained checks.

Also fixes a typo in the name of the isinstance(obj, int) primitive (builtints.isinstance).

Benchmarks in ns, Python 3.12:

| | master | this PR |
| isinstance(x, complex) | 43.0 | 5.9 |
| isinstance(x, (float, complex)) | 106.0 | 7.1 |
| isinstance(x, (bytes, bytearray, memoryview)) | 101.8 | 5.4 |
| type(x) is complex | 22.2 | 4.3 |

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

Thanks for the PR! This changes behavior subtly by not supporting __instancecheck__, among other things. There are other places where we don't fully support some dynamic isinstance check functionality, so I don't think that this makes things significantly worse. Having primitive types for all of the target types would mostly fix the issue, but that's a somewhat more involved change.

@JukkaL
JukkaL merged commit d850d44 into python:master Oct 5, 2026
18 checks passed
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