New submission from STINNER Victor <[email protected]>:
Last years, I started to add "CAST" macros like:
#define _PyObject_CAST(op) ((PyObject*)(op))
#define _PyType_CAST(op) (assert(PyType_Check(op)), (PyTypeObject*)(op))
Example of usage:
#define PyObject_TypeCheck(ob, type) PyObject_TypeCheck(_PyObject_CAST(ob),
type)
These macros avoids parenthesis. Example without CAST macro:
#define PyCFunction_GET_FLAGS(func) \
(((PyCFunctionObject *)func) -> m_ml -> ml_flags)
Currently, inline cast requires adding parenthesis:
((PyCFunctionObject *)func)
IMO it's more readable with a CAST macro:
#define _PyCFunction_CAST(func) ((PyCFunctionObject *)func)
#define PyCFunction_GET_FLAGS(func) \
(_PyCFunction_CAST(func)->m_ml->ml_flags)
I propose to add more CAST macros.
By the way, the current Python C API is not fully compatible with C++.
"(type)expr" C syntax is seen as "old-style cast" in C++ which recommends
static_cast<type>(expr), reinterpret_cast<type>(expr), or another kind of cast.
But I prefer to discuss C++ in a separated issue ;-) IMO without considering
C++, adding CAST macros is worth it for readability.
I am preparing pull requests for add CAST macros and use existing CAST macros.
----------
components: C API
messages: 416350
nosy: vstinner
priority: normal
severity: normal
status: open
title: [C API] Add private "CAST" macros to clean up casts in C code
versions: Python 3.11
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue47164>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com