KEMBAR78
[mypyc] Use PyList_Check for isinstance(obj, list) by p-sawicki · Pull Request #19416 · python/mypy · GitHub
Skip to content

Conversation

p-sawicki
Copy link
Collaborator

Added a primitive to translate isinstance(obj, list) to PyList_Check(obj) instead of PyObject_IsInstance(obj, type), as the former is faster. Similar primitives can be added for other built-in types, which I plan to do in next PRs.

def f(x) -> bool:
    return isinstance(x, list)

def bench(n: int) -> None:
    for x in range(n):
        if x % 2 == 0:
            f(x)
        else:
            f([x])

from time import time
bench(1000)
t0 = time()
bench(50 * 1000 * 1000)
print(time() - t0)

Using the above benchmark, execution time goes from ~1.4s to ~0.97s on my machine.

class list:
pass

def test() -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

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

I don't think this gets executed, since the test runner looks for a test_ prefix. Also, can you merge the new test cases under one [case ...] and add multiple def test_... methods for sub test cases? Each top-level test case has significant constant overhead, so having a few, bigger test cases makes the test suite run faster.


[case testIsInstance]
from copysubclass import subc
def test() -> None:
Copy link
Collaborator

Choose a reason for hiding this comment

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

Similar to my other comment about test_ prefix.

Copy link
Collaborator

@JukkaL JukkaL left a comment

Choose a reason for hiding this comment

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

Thanks for the updates! Looks good now.

@JukkaL JukkaL merged commit 02c9766 into python:master Jul 9, 2025
13 checks passed
@p-sawicki p-sawicki deleted the specialize-isinstance-list branch July 9, 2025 19:56
JukkaL pushed a commit that referenced this pull request Jul 11, 2025
Adding back a test for `next` with a list iterator as argument.
Previously this test only checked if compilation succeeded so I have
removed it in #19416, now it calls the test function and checks the
result.
JukkaL pushed a commit that referenced this pull request Jul 15, 2025
Follow-up to #19416 adding primitives for `isinstance(obj, type)` where
type is built-in.
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