You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
This is about python/cpython#76535 (Unclear intention of deprecating Py_UNICODE_TOLOWER / Py_UNICODE_TOUPPER). As far as I understand, these were deprecated in the versions 3.3 - 3.12, but were undeprecated in 3.13. However, they're still pretty unusable, because of the fact that changing the case of a Unicode character might lead to two or more characters.
There's alternative APIs for this that do the right thing, _PyUnicode_ToLowerFull and friends. I'm suggesting to rename these to PyUnicode_ToLower etc. and expose them as public API. An implementation can be found on python/cpython#136176.
Some context: I'm working on making NumPy string array operations faster. Up until now, these were working by converting the array item (a UCS4 buffer) to a PyObject, calling the corresponding str method and then converting the result back to a UCS4 buffer to put back into the array. Instead of doing this, we're writing fast string ufuncs that operate on the buffer without having to do the back-and-forth with PyObjects. We've been able to do this with almost all of the string operations by traversing the array, then traversing the UCS4 buffer and doing the operation codepoint by codepoint. The only ones missing right now are lower and friends, because we don't have a good way of doing that same thing.
the names should advertise that the functions don't work on str objects. Perhaps PyUnicode_CodepointToLower or even PyUCS4_ToLower.
Should we should also expose the buffer size needed to do any of these operations on any character (i.e. 3 for Unicode 16.0)? This can't be part of the limited API, but might be quite helpful elsewhere.
the names should advertise that the functions don't work on str objects. Perhaps PyUnicode_CodepointToLower or even PyUCS4_ToLower.
I like PyUCS4_ToLower. If everyone agrees, I can rename the new APIs to that.
Should we should also expose the buffer size needed to do any of these operations on any character (i.e. 3 for Unicode 16.0)? This can't be part of the limited API, but might be quite helpful elsewhere.
@serhiy-storchaka proposed this as well if I remember correctly. Should we add macros that define the buffer size?
With my NumPy maintainer hat on: it'd be really nice to be able to add fast implementations for np.strings.upper() and np.strings.lower(). What we currently do is very suboptimal.
These functions will be called in a tight loop. Passing an extra argument, testing it in the function, and checking the result after each function call will add unnecessary overhead. Changing the result type from int to Py_ssize_t can also affect this.
And since a these functions are called in a tight loop in the implementations of the string methods, this will affect each program.
There is no need to do all these checks for each character in a loop. The maximal size of the buffer is small, just use the buffer of the maximal capacity. Check it's size outside of the loop. To make it future proof, we should provide the maximal buffer size as a macro and and as a function. You can create a buffer of static size and then check that its size matches the runtime size.
In summary, I propose to return to the original interface of private functions and provide a macro and a function for the maximal buffer size.
Passing an extra argument, testing it in the function, and checking the result after each function call will add unnecessary overhead.
I don't think that it's a good API if we don't check the size (ex: Py_ssize_t PyUCS4_ToLower(Py_UCS4 ch, Py_UCS4 *buffer)). It can lead to buffer overflow, no? I prefer to offer a safe API.
Are you able to check if the size check adds significant overhead?
Not easily - I'd need to implement ufuncs in NumPy that depend on a patched version of CPython.
But I also don't think size checks would be a big deal. To give you an idea of how slow our current implementation is:
In [4]: chars = list(string.ascii_letters + string.digits)
...: chars = np.array(chars, dtype="U1")
...: ret = np.random.choice(chars, size=100 * 10000, replace=True)
...: random_string_list = ret.view("U100")
In [5]: random_string_list.shape
Out[5]: (10000,)
In [6]: %timeit np.strings.rstrip(random_string_list)
193 μs ± 683 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
In [7]: %timeit np.strings.upper(random_string_list)
2.01 ms ± 6.97 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
The current implementation needs to individually convert each array item to a PyStr, call str.upper() on that string, then convert the result back to a numpy unicode string.
Comparing with rstrip, which is implemented as a ufunc, you can see that all that copying adds a lot of unnecessary overhead.
We could of course add our own unicode data to NumPy and do operations like capitalization using that, but then we would have to be very careful to make sure we're doing exactly the same thing as CPython (if we care about that). If we get an API in CPython we can use like the other string operations, we get that "for free".
We did actually copy the string searching utilities from CPython, converted them to C++, and added them to NumPy. But I'd prefer not to do that more of that than we already did.
To really make people handle multi-char characters properly, we should only offer string functions (where the output length != input length), and not character functions.
Yeah. But can we ignore the can of worms of UCS-4 usually being wasteful?
can we ignore the can of worms of UCS-4 usually being wasteful?
I think it's more of an elephant in the room 😉
I was okay with being able to pass only a single output character, provided the caller also passes the value "1" to indicate that they've only passed a single output character. I was not okay with the caller always having to pass a multi-character buffer of a size specified in a macro.
the proposed API: converts one character at a time -- lots of function call overhead unless the strings are known to be short
UCS4 string to UCS4 string: lots of memory overhead if you don't need UCS4
Multiple format support (UCS1/2/4 string to UCS1/2/4 string): now we need to describe string format, which is a pain; also in the future we might want to change the str representation and that would leave code only used for existing APIs
str object to str object: lots of copying overhead. OTOH, this already exists.
IMO, the proposed API is a reasonable compromise here, especially if we know it's good enough for NumPy.
I would prefer to expose Py_ssize_t PyUCS4_GetCaseConversionBufferSize(void) function instead of #define PyUCS4_CASE_CONVERSION_BUFFER_SIZE 3. For the stable ABI, it avoids having to rebuild the C extension if the macro value changes.
It also means you need to allocate buffers at run-time; I doubt anyone will bother with that.
Are we adding these to the stable ABI? A function would makes sense there. I imagine people would still pick a static buffer size, but they could check it against PyUCS4_GetCaseConversionBufferSize() once at startup.
@serhiy-storchaka, do you want to block this API? Or vote for the counterproposal?
I support the counterproposal, with addition that we also expose the macro PyUCS4_CASE_CONVERSION_BUFFER_SIZE. Preferably also change the return type to int.
If this will fail, can we at least keep _PyUnicode_ToLowerFull() for internal use (in str.lower)? It does not add overhead PyUnicode_ToLower() from the original proposition, no matter how small it is.
can we at least keep _PyUnicode_ToLowerFull() for internal use (in str.lower)? It does not add overhead PyUnicode_ToLower() from the original proposition, no matter how small it is.
Yes, of course.
We can also (outside stable ABI) define this in the header as something like:
There's now two competing proposals that clash with one another. One is supported 4-1, while the other one is 1-4 and it appears like there's no way to reach a consensus.
I'm planning to open a PR to add these function to the Unstable API this week. This is the only way forward I can see so that NumPy can get a benefit of up to a 500x speed-up for these functions.
If this will fail, can we at least keep _PyUnicode_ToLowerFull() for internal use (in str.lower)?
For internal use, we can use whatever we want. I don't think that contraints of Python internals should not be taken in account when writing a public C API which has other constraints.
I would prefer to have a public API with Py_ssize_t size parameter, but the internal API can be different.
This is the only way forward I can see so that NumPy can get a benefit of up to a 500x speed-up for these functions.
The Py_ssize_t size parameter is 15% slower than the private API without it, but 15% is not significant compared to a 500x speed-up :-)
Activity
encukou commentedon Jul 22, 2025
Works for me, but IMO
the names should advertise that the functions don't work on
strobjects. PerhapsPyUnicode_CodepointToLoweror evenPyUCS4_ToLower.Should we should also expose the buffer size needed to do any of these operations on any character (i.e.
3for Unicode 16.0)? This can't be part of the limited API, but might be quite helpful elsewhere.lysnikolaou commentedon Jul 22, 2025
Thanks @encukou for the quick response on this!
I like
PyUCS4_ToLower. If everyone agrees, I can rename the new APIs to that.@serhiy-storchaka proposed this as well if I remember correctly. Should we add macros that define the buffer size?
encukou commentedon Jul 23, 2025
IMO, a single
#define PyUCS4_CASE_CONVERSION_BUFFER_SIZE 3would do. There's not much to be gained in making it specific to each function.malemburg commentedon Jul 27, 2025
Same here.
lysnikolaou commentedon Jul 28, 2025
Addressed all feedback on the PR.
encukou commentedon Jul 29, 2025
Add
PyUCS4_ToLower,PyUCS4_ToUpper,PyUCS4_ToTitle,PyUCS4_ToFolded,PyUCS4_CASE_CONVERSION_BUFFER_SIZEngoldbaum commentedon Aug 1, 2025
With my NumPy maintainer hat on: it'd be really nice to be able to add fast implementations for
np.strings.upper()andnp.strings.lower(). What we currently do is very suboptimal.serhiy-storchaka commentedon Aug 2, 2025
These functions will be called in a tight loop. Passing an extra argument, testing it in the function, and checking the result after each function call will add unnecessary overhead. Changing the result type from int to Py_ssize_t can also affect this.
And since a these functions are called in a tight loop in the implementations of the string methods, this will affect each program.
There is no need to do all these checks for each character in a loop. The maximal size of the buffer is small, just use the buffer of the maximal capacity. Check it's size outside of the loop. To make it future proof, we should provide the maximal buffer size as a macro and and as a function. You can create a buffer of static size and then check that its size matches the runtime size.
In summary, I propose to return to the original interface of private functions and provide a macro and a function for the maximal buffer size.
vstinner commentedon Aug 4, 2025
What is the API of PyUCS4_ToLower()?
encukou commentedon Aug 7, 2025
From the PR:
@lysnikolaou, would the speedup from not checking on each call be noticeable?
vstinner commentedon Aug 7, 2025
I don't think that it's a good API if we don't check the size (ex:
Py_ssize_t PyUCS4_ToLower(Py_UCS4 ch, Py_UCS4 *buffer)). It can lead to buffer overflow, no? I prefer to offer a safe API.encukou commentedon Aug 12, 2025
@ngoldbaum: Are you able to check if the
sizecheck adds significant overhead?vstinner commentedon Aug 13, 2025
I ran benchmarks: see python/cpython#136176 (comment)
ngoldbaum commentedon Aug 13, 2025
Not easily - I'd need to implement ufuncs in NumPy that depend on a patched version of CPython.
But I also don't think size checks would be a big deal. To give you an idea of how slow our current implementation is:
The current implementation needs to individually convert each array item to a PyStr, call
str.upper()on that string, then convert the result back to a numpy unicode string.Comparing with rstrip, which is implemented as a ufunc, you can see that all that copying adds a lot of unnecessary overhead.
We could of course add our own unicode data to NumPy and do operations like capitalization using that, but then we would have to be very careful to make sure we're doing exactly the same thing as CPython (if we care about that). If we get an API in CPython we can use like the other string operations, we get that "for free".
We did actually copy the string searching utilities from CPython, converted them to C++, and added them to NumPy. But I'd prefer not to do that more of that than we already did.
28 remaining items
encukou commentedon Nov 17, 2025
Yeah. But can we ignore the can of worms of UCS-4 usually being wasteful?
zooba commentedon Nov 17, 2025
I think it's more of an elephant in the room 😉
I was okay with being able to pass only a single output character, provided the caller also passes the value "1" to indicate that they've only passed a single output character. I was not okay with the caller always having to pass a multi-character buffer of a size specified in a macro.
encukou commentedon Nov 24, 2025
Stepping back, I see several ways to do this...
strrepresentation and that would leave code only used for existing APIsstrobject tostrobject: lots of copying overhead. OTOH, this already exists.IMO, the proposed API is a reasonable compromise here, especially if we know it's good enough for NumPy.
encukou commentedon Dec 2, 2025
@serhiy-storchaka, do you want to block this API? Or vote for the counterproposal?
vstinner commentedon Dec 3, 2025
I would prefer to expose
Py_ssize_t PyUCS4_GetCaseConversionBufferSize(void)function instead of#define PyUCS4_CASE_CONVERSION_BUFFER_SIZE 3. For the stable ABI, it avoids having to rebuild the C extension if the macro value changes.encukou commentedon Jan 12, 2026
It also means you need to allocate buffers at run-time; I doubt anyone will bother with that.
Are we adding these to the stable ABI? A function would makes sense there. I imagine people would still pick a static buffer size, but they could check it against
PyUCS4_GetCaseConversionBufferSize()once at startup.@serhiy-storchaka, do you want to block this API? Or vote for the counterproposal?
serhiy-storchaka commentedon Jan 15, 2026
I support the counterproposal, with addition that we also expose the macro PyUCS4_CASE_CONVERSION_BUFFER_SIZE. Preferably also change the return type to
int.If this will fail, can we at least keep
_PyUnicode_ToLowerFull()for internal use (instr.lower)? It does not add overheadPyUnicode_ToLower()from the original proposition, no matter how small it is.encukou commentedon Jan 23, 2026
Yes, of course.
We can also (outside stable ABI) define this in the header as something like:
so that you get the fast version whenever
sizeis a compile-time constant.That doesn't change the API surface though :)
lysnikolaou commentedon Jan 26, 2026
There's now two competing proposals that clash with one another. One is supported 4-1, while the other one is 1-4 and it appears like there's no way to reach a consensus.
I'm planning to open a PR to add these function to the Unstable API this week. This is the only way forward I can see so that NumPy can get a benefit of up to a 500x speed-up for these functions.
encukou commentedon Feb 2, 2026
@serhiy-storchaka, do you still want to block the first proposal?
vstinner commentedon Feb 6, 2026
@serhiy-storchaka:
For internal use, we can use whatever we want. I don't think that contraints of Python internals should not be taken in account when writing a public C API which has other constraints.
I would prefer to have a public API with
Py_ssize_t sizeparameter, but the internal API can be different.The
Py_ssize_t sizeparameter is 15% slower than the private API without it, but 15% is not significant compared to a 500x speed-up :-)encukou commentedon Feb 13, 2026
@serhiy-storchaka, do you still want to block the first proposal?
encukou commentedon Mar 2, 2026
ping @serhiy-storchaka
encukou commentedon Apr 7, 2026
ping @serhiy-storchaka
encukou commentedon Apr 20, 2026
ping @serhiy-storchaka