(Opened per a suggestion in the C-API WG issue.)
Historically, in CPython we have functions like _Py_c_sum and _Py_c_prod to do arithmetic with Py_complex (a custom type for complex numbers). Recent pr python/cpython#124829 added support for mixed-mode arithmetic and this API was extended with functions like _Py_cr_prod (i.e. when one argument is a real number). (JFR: this new C-API is hidden for now.)
It was suggested by @vstinner in python/cpython#124829 (comment) either to remove this from the public API or rename properly (e.g. like Py_complex_add()
and Py_complex_add_real()
, in the GNU GSL style).
Of course, people could use PyNumber_*()
API. Main motivation to provide a different C-API for doing correct complex arithmetic — is speed. But with python/cpython#124829 — complex arithmetic in CPython follows to most implementations of the C99+ Annex G. So, users can use native double _Complex
type instead of the Py_complex
. Removing low-level arithmetic API & Py_complex
struct possibly open a door to eventually switch CPython to use native complex type (double _Complex
) internally (like for floats).
Proposal:
- deprecate
_Py_c_*()
functions - add
PyComplex_From/As*()
methods to import/export from/to native complex type. (conditionally) - deprecate
Py_complex
struct,PyComplex_FromCComplex()
andPyComplex_AsCComplex()
. - (in even more distant future) switch to using
double _Complex
internally
I see several arguments to keep these functions (from high to low priority):
- special arithmetic functions will make sense if we go beyond most Annex G implementations, i.e. add support for pure-imaginary numbers. This was recently suggested here. Probably, we can conclude that this proposal (which I’m fan of) has no enough support.
- not all Tier 1 PEP 11’s platforms have Annex G support: it’s Windows with MSVC. I don’t know if here are some plans to add such support. On another hand, this platform has a different native complex type,
_Dcomplex
, with some arithmetic primitives to do math with. People could use this type or some external library (like GSL) to do complex arithmetic. - current Annex G has no special case for
real/complex
division (which we have in our implementation since python/cpython#124829). So, current CPython complex arithmetic has a small incompatibility with the C standard. This is something, going to be fixed by N3460 in upcoming standard.
CPython issue: Make _Py_c_sum(), _Py_c_diff(), etc (elementary operations on Py_complex) - part of the public API · Issue #128813 · python/cpython · GitHub
C-API WG issue: Remove public low-level API functions for Py_complex? · Issue #56 · capi-workgroup/decisions · GitHub