Skip to content

[mypyc] Add primitive for <type>.__name__ #19683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 18, 2025
Merged

[mypyc] Add primitive for <type>.__name__ #19683

merged 2 commits into from
Aug 18, 2025

Conversation

JukkaL
Copy link
Collaborator

@JukkaL JukkaL commented Aug 18, 2025

This seems quite common in real-world code, including in performance-critical functions. Python 3.11 added a C API function for this, which we use here.

The primitive works for arbtirary objects, but only type objects have a specialized code path. Other use cases of __name__ seem typically less performance-sensitive.

This PR makes this micro-benchmark 2.0x faster on Python 3.13:

from typing import Iterator

class FooBar: pass

def foo(x: type[object], n: int) -> str:
    for a in range(n):
        s = x.__name__
    return s

def bench(n: int) -> None:
    for i in range(n):
        foo(FooBar, 1000)

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

JukkaL added 2 commits August 18, 2025 15:09
This is quite common in real-world code. Python 3.11 added a C API
function for this, which we use here.

The primitive works for arbtirary objects, but only type objects have
a specialized code path. Other use cases of `__name__` seem typically
less performance-sensitive.

This PR makes this micro-benchmark 2.0x faster on Python 3.13:
```
from typing import Iterator

class FooBar: pass

def foo(x: type[object], n: int) -> str:
    for a in range(n):
        s = x.__name__
    return s

def bench(n: int) -> None:
    for i in range(n):
        foo(FooBar, 1000)

from time import time
bench(50 * 1000)
t0 = time()
bench(50 * 1000)
print(time() - t0)
```
@JukkaL JukkaL merged commit 38eeff8 into master Aug 18, 2025
13 checks passed
@JukkaL JukkaL deleted the mypyc-dunder-name branch August 18, 2025 15:43
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