Serhiy Storchaka writes:
Python integers have arbitrary precision. For serialization and interpolation with other programs and libraries we need to represent them [...]. [In the case of non-standard precisions,] [t]here are private C API functions _PyLong_AsByteArray and _PyLong_FromByteArray, but they are for internal use only.
I am planning to add public analogs of these private functions, but more powerful and convenient.
PyObject *PyLong_FromBytes(const void *buf, Py_ssize_t size, int byteorder, int signed)
Py_ssize_t PyLong_AsBytes(PyObject *o, void *buf, Py_ssize_t n, int byteorder, int signed, int *overflow)
I don't understand why such a complex API is useful as a public facility. For example, I've often thought it would be amusing (and maybe useful) to have PyXEmacs, which would still be a Lisp application, but capable of delegating some computations to a subinterpreter. Now, XEmacs's native representations are none (ie, overflow is signaled), GMP (GNU multiprecision), and MP (BSD multiprecision). XEmacs supports bigratios and bigfloats as well as bigints. So I might want PyLong_AsGMPInt and PyLong_AsGMPRatio as well as the corresponding functions for MP, and maybe even PyLong_AsGMPFloat. The obvious way to write those is <library constructor>(str(python_integer)), I think. The same approach is easily generalized to Decimal and Fraction, although you might need to use format() instead of str(), and extract precision information to pass to the library constructor. How often would someone need something more performant? I don't think PyLong_AsBytes would be useful to me, since I'll have to write pybytes_to_gmp_int etc, etc, anyway. I admit that this is both specific to me and at present imaginary :-), but it seems to me that most applications that can accept non-standard-precision integers will very likely be using such libraries. In the unlikely event that an application needs to squeeze out that tiny bit of performance, I guess the library constructors all accept buffers of bytes, too, probably with a similarly complex API that can handle whatever the Python ABI throws at them. In which case why not just expose the internal functions? Is it at all likely that that representation would ever change? Are there likely to be applications that use idiosyncratic representations of high-precision integers that this API would handle directly?