Skip to content

[mypyc] Add primitives for str.capitalize, casefold, swapcase and title - #22413

Open
Jahongir-Qurbonov wants to merge 3 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-str-case
Open

Jahongir-Qurbonov wants to merge 3 commits into
python:masterfrom
Jahongir-Qurbonov:mypyc-str-case

Conversation

@Jahongir-Qurbonov

@Jahongir-Qurbonov Jahongir-Qurbonov commented Nov 9, 2026 •

Copy link
Copy Markdown
Contributor

Add primitives for str.capitalize(), str.casefold(), str.swapcase() and str.title().

ASCII strings use a direct fast path. Other strings fall back to calling the str method, similar to str.lower() / str.upper() on Python 3.13+, since the full Unicode case mappings (special casing, title case characters, final sigma, etc.) are not available through the public C API.

Tests compare the results against the generic implementation (through Any) for all ASCII strings of length 1 and 2 (and some of length 3), and various ASCII and non-ASCII strings. The result is always an exact str, also for str subclasses. The fallback calls the method on str (not on the type of the object), so a subclass that overrides one of these methods can't make the result something other than a str.

Micro-benchmark (compiled code, 3.2M calls, best of 15, before -> after, Python 3.13):

Method Short ASCII (11 chars) Long ASCII (176 chars)
capitalize() 0.257s -> 0.082s 1.755s -> 0.251s
casefold() 0.125s -> 0.081s 0.285s -> 0.250s
swapcase() 0.221s -> 0.087s 1.439s -> 0.416s
title() 0.259s -> 0.085s 2.026s -> 0.886s

Non-ASCII strings are roughly unchanged.

Part of mypyc/mypyc#644.

…sses

For non-ASCII strings, look up the method on str instead of on the type of
the object, so that an override in a str subclass can't make the result
something other than a str.
# Conflicts:
#	mypyc/test-data/fixtures/ir.py
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