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
Add unified C API for accessing bytes and bytearray #80246
Comments
It would be useful to have a shared API for consuming bytes and bytearrays. At present, I need to write very similar code twice. Some existing codebases only support bytes (perhaps forgetting bytearrays exist). Adding support for bytearray would be trivial if there was a shared API. These are the functions/macros that can have "BytesOrByteArray" equivalents:
Here are some example implementations for the macros: #define PyBytesOrByteArray_Check(ob) (PyBytes_Check(ob) || PyByteArray_Check(ob))
#define PyBytesOrByteArray_AS_STRING(ob) (PyBytes_Check(ob) ? PyBytes_AS_STRING(ob) : PyByteArray_AS_STRING(ob))
#define PyBytesOrByteArray_GET_SIZE(ob) #define PyByteArray_GET_SIZE(self) (assert(PyBytesOrByteArray_Check(self)), Py_SIZE(self)) |
I remove 2.7 because this branch is in bugfix mode, no new features. |
Stéphane: Please don't add me to the nosy list of bugs. |
What is your use case for this? Is that something that can use the buffer API instead of these low-level APIs? |
The unified C API already exists. It is called the buffer protocol. https://docs.python.org/3/c-api/buffer.html#buffer-related-functions |
My use-case is modifying existing code that supports bytes to also support bytearray. The buffer protocol, which I didn't know of, feels slightly complicated for my use-case. For now I opted to adding these macros myself, only changing 3 lines. |
If you need to support only bytes and bytearray, but not other bytes-like object, this is a too special case. It is easy to write your own macros or functions that wrap existing C API. Other option -- duplicate the code and replace PyBytes_ with PyByteArray_. In all cases be aware abot differences between bytes and bytearray: bytarray can change its content and size, saved values of PyByteArray_AS_STRING(ob) and PyByteArray_GET_SIZE(self) can not be used after executing arbitrary code in destructors or releasing GIT. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: