How to convert a unicode string to upper/lower/title case using Python's C API avoiding functions deprecated in Python 3.3?

Viewed 63

As described in

https://docs.python.org/3/c-api/unicode.html#unicode-character-properties,

Py_UNICODE_TOUPPER and friends are deprecated since Python 3.3, when PEP 393 was implemented. However, there does not seem any replacement. In particular, the C API does not seem to allow calls to the underlying C functions of methods such as 'abc'.upper().

Does this mean that the C API, since Python 3.3, no longer supports these basic str conversions? Is there any workaround?

1 Answers

You can call the methods. See the Call Protocol.

Example:

test.c

#include <Python.h>

__declspec(dllexport)
PyObject* upper(PyObject* arg) {
    return PyObject_CallMethod(arg,"upper",NULL);
}

Demo using ctypes:

>>> from ctypes import *
>>> dll = PyDLL('./test')
>>> dll.upper.argtypes = py_object,
>>> dll.upper.restype = py_object
>>> dll.upper('hello')
'HELLO'
Related