Skip to content

Expose PyUnicode_ToLower and friends #71

Open

Description

@lysnikolaou

Hey folks! 👋

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.

Activity

  1. encukou commented on Jul 22, 2025

    @encukou
    Collaborator

    Works for me, but IMO

    • 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.

  2. lysnikolaou commented on Jul 22, 2025

    @lysnikolaou
    Author

    Thanks @encukou for the quick response on this!

    • 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?

  3. encukou commented on Jul 23, 2025

    @encukou
    Collaborator

    IMO, a single #define PyUCS4_CASE_CONVERSION_BUFFER_SIZE 3 would do. There's not much to be gained in making it specific to each function.

  4. malemburg commented on Jul 27, 2025

    @malemburg

    I like PyUCS4_ToLower. If everyone agrees, I can rename the new APIs to that.

    Same here.

  5. lysnikolaou commented on Jul 28, 2025

    @lysnikolaou
    Author

    Addressed all feedback on the PR.

  6. encukou commented on Jul 29, 2025

    @encukou
    Collaborator

    Add PyUCS4_ToLower, PyUCS4_ToUpper, PyUCS4_ToTitle, PyUCS4_ToFolded, PyUCS4_CASE_CONVERSION_BUFFER_SIZE

  7. added
    vote
    on Jul 29, 2025
  8. ngoldbaum commented on Aug 1, 2025

    @ngoldbaum

    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.

  9. serhiy-storchaka commented on Aug 2, 2025

    @serhiy-storchaka

    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.

  10. vstinner commented on Aug 4, 2025

    @vstinner
    Contributor

    What is the API of PyUCS4_ToLower()?

  11. encukou commented on Aug 7, 2025

    @encukou
    Collaborator

    From the PR:

    Py_ssize_t PyUCS4_ToLower(Py_UCS4 ch, Py_UCS4 *buffer, Py_ssize_t size)
    Py_ssize_t PyUCS4_ToUpper(Py_UCS4 ch, Py_UCS4 *buffer, Py_ssize_t size)
    Py_ssize_t PyUCS4_ToTitle(Py_UCS4 ch, Py_UCS4 *buffer, Py_ssize_t size)
    Py_ssize_t PyUCS4_ToFolded(Py_UCS4 ch, Py_UCS4 *buffer, Py_ssize_t size)
    #define PyUCS4_CASE_CONVERSION_BUFFER_SIZE 3

    @lysnikolaou, would the speedup from not checking on each call be noticeable?

  12. vstinner commented on Aug 7, 2025

    @vstinner
    Contributor

    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.

  13. encukou commented on Aug 12, 2025

    @encukou
    Collaborator

    @ngoldbaum: Are you able to check if the size check adds significant overhead?

  14. vstinner commented on Aug 13, 2025

    @vstinner
    Contributor

    I ran benchmarks: see python/cpython#136176 (comment)

  15. ngoldbaum commented on Aug 13, 2025

    @ngoldbaum

    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.

  16. 28 remaining items

  17. encukou commented on Nov 17, 2025

    @encukou
    Collaborator

    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?

  18. zooba commented on Nov 17, 2025

    @zooba

    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.

  19. encukou commented on Nov 24, 2025

    @encukou
    Collaborator

    Stepping back, I see several ways to do this...

    • 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.

  20. encukou commented on Dec 2, 2025

    @encukou
    Collaborator

    @serhiy-storchaka, do you want to block this API? Or vote for the counterproposal?

  21. vstinner commented on Dec 3, 2025

    @vstinner
    Contributor

    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.

  22. encukou commented on Jan 12, 2026

    @encukou
    Collaborator

    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?

  23. serhiy-storchaka commented on Jan 15, 2026

    @serhiy-storchaka

    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.

  24. encukou commented on Jan 23, 2026

    @encukou
    Collaborator

    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:

    static inline Py_ssize_t
    PyUCS4_ToLower(Py_UCS4 ch, Py_UCS4 *buffer, Py_ssize_t size)
    {
        if (size >= PyUCS4_CASE_CONVERSION_BUFFER_SIZE) {
            return _PyUnicode_ToLowerFull(ch, buffer);
        } else {
            return _PyUCS4_ToLower_impl(ch, buffer, size);
        }
    }

    so that you get the fast version whenever size is a compile-time constant.

    That doesn't change the API surface though :)

  25. lysnikolaou commented on Jan 26, 2026

    @lysnikolaou
    Author

    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.

  26. encukou commented on Feb 2, 2026

    @encukou
    Collaborator

    @serhiy-storchaka, do you still want to block the first proposal?

  27. vstinner commented on Feb 6, 2026

    @vstinner
    Contributor

    @serhiy-storchaka:

    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 :-)

  28. encukou commented on Feb 13, 2026

    @encukou
    Collaborator

    @serhiy-storchaka, do you still want to block the first proposal?

  29. encukou commented on Mar 2, 2026

    @encukou
    Collaborator
  30. encukou commented on Apr 7, 2026

    @encukou
    Collaborator
  31. encukou commented on Apr 20, 2026

    @encukou
    Collaborator
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    vote

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions