Skip to content

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

Open
rheard wants to merge 2 commits into
python:masterfrom
rheard:isinstance-primatives
Open

rheard wants to merge 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 |

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