1

In Python2's C API there was long PyInt_AS_LONG() function which allowed a very quick creation of a C long from a Python2 int.

Is there a quick way to check, using Python3 C API, that an int (which is actually an arbitrary precision integer) fits into C long?

One can call PyLong_AsLong(), but this appears to do unnecessary work. There ought to be a function to get the size of the memory block used to store the number, but I can't find anything in the docs.

This has to be done in C, so I can't directly use Python arithmetic comparison. Although I can, in principle, call PyObject_RichCompare(), it looks like an overkill.

Dima Pasechnik
  • 336
  • 4
  • 16
  • 1
    I need to do this in C, so I can't just do `<`. – Dima Pasechnik Aug 12 '23 at 14:54
  • 1
    What is the "unnecessary work" you think `PyLong_AsLong()` is doing? If it's just that you want a flag rather than an actual exception generated for out-of-range values - try `PyLong_AsLongAndOverflow()` instead. – jasonharper Aug 12 '23 at 15:52
  • I don't know how Python stores its integers. Thanks for pointing out `PyLong_AsLongAndOverflow` - I suspect it'll be much faster than `PyLong_AsLong`, as exceptions are slow. – Dima Pasechnik Aug 12 '23 at 16:28

0 Answers0