Debian Codegraph @

Doc/c-api/long.rst

raw
1 .. highlight:: c
2
3 .. _longobjects:
4
5 Integer Objects
6 ---------------
7
8 .. index:: pair: object; long integer
9 pair: object; integer
10
11 All integers are implemented as "long" integer objects of arbitrary size.
12
13 On error, most ``PyLong_As*`` APIs return ``(return type)-1`` which cannot be
14 distinguished from a number. Use :c:func:`PyErr_Occurred` to disambiguate.
15
16 .. c:type:: PyLongObject
17
18 This subtype of :c:type:`PyObject` represents a Python integer object.
19
20
21 .. c:var:: PyTypeObject PyLong_Type
22
23 This instance of :c:type:`PyTypeObject` represents the Python integer type.
24 This is the same object as :class:`int` in the Python layer.
25
26
27 .. c:function:: int PyLong_Check(PyObject *p)
28
29 Return true if its argument is a :c:type:`PyLongObject` or a subtype of
30 :c:type:`PyLongObject`. This function always succeeds.
31
32
33 .. c:function:: int PyLong_CheckExact(PyObject *p)
34
35 Return true if its argument is a :c:type:`PyLongObject`, but not a subtype of
36 :c:type:`PyLongObject`. This function always succeeds.
37
38
39 .. c:function:: PyObject* PyLong_FromLong(long v)
40
41 Return a new :c:type:`PyLongObject` object from *v*, or ``NULL`` on failure.
42
43 .. impl-detail::
44
45 CPython keeps an array of integer objects for all integers
46 between ``-5`` and ``256``. When you create an int in that range
47 you actually just get back a reference to the existing object.
48
49
50 .. c:function:: PyObject* PyLong_FromUnsignedLong(unsigned long v)
51
52 Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long`, or
53 ``NULL`` on failure.
54
55
56 .. c:function:: PyObject* PyLong_FromSsize_t(Py_ssize_t v)
57
58 Return a new :c:type:`PyLongObject` object from a C :c:type:`Py_ssize_t`, or
59 ``NULL`` on failure.
60
61
62 .. c:function:: PyObject* PyLong_FromSize_t(size_t v)
63
64 Return a new :c:type:`PyLongObject` object from a C :c:type:`size_t`, or
65 ``NULL`` on failure.
66
67
68 .. c:function:: PyObject* PyLong_FromLongLong(long long v)
69
70 Return a new :c:type:`PyLongObject` object from a C :c:expr:`long long`, or ``NULL``
71 on failure.
72
73
74 .. c:function:: PyObject* PyLong_FromUnsignedLongLong(unsigned long long v)
75
76 Return a new :c:type:`PyLongObject` object from a C :c:expr:`unsigned long long`,
77 or ``NULL`` on failure.
78
79
80 .. c:function:: PyObject* PyLong_FromInt32(int32_t value)
81 PyObject* PyLong_FromInt64(int64_t value)
82
83 Return a new :c:type:`PyLongObject` object from a signed C
84 :c:expr:`int32_t` or :c:expr:`int64_t`, or ``NULL``
85 with an exception set on failure.
86
87 .. versionadded:: 3.14
88
89
90 .. c:function:: PyObject* PyLong_FromUInt32(uint32_t value)
91 PyObject* PyLong_FromUInt64(uint64_t value)
92
93 Return a new :c:type:`PyLongObject` object from an unsigned C
94 :c:expr:`uint32_t` or :c:expr:`uint64_t`, or ``NULL``
95 with an exception set on failure.
96
97 .. versionadded:: 3.14
98
99
100 .. c:function:: PyObject* PyLong_FromDouble(double v)
101
102 Return a new :c:type:`PyLongObject` object from the integer part of *v*, or
103 ``NULL`` on failure.
104
105
106 .. c:function:: PyObject* PyLong_FromString(const char *str, char **pend, int base)
107
108 Return a new :c:type:`PyLongObject` based on the string value in *str*, which
109 is interpreted according to the radix in *base*, or ``NULL`` on failure. If
110 *pend* is non-``NULL``, *\*pend* will point to the end of *str* on success or
111 to the first character that could not be processed on error. If *base* is ``0``,
112 *str* is interpreted using the :ref:`integers` definition; in this case, leading
113 zeros in a non-zero decimal number raises a :exc:`ValueError`. If *base* is not
114 ``0``, it must be between ``2`` and ``36``, inclusive. Leading and trailing
115 whitespace and single underscores after a base specifier and between digits are
116 ignored. If there are no digits or *str* is not NULL-terminated following the
117 digits and trailing whitespace, :exc:`ValueError` will be raised.
118
119 .. seealso:: :c:func:`PyLong_AsNativeBytes()` and
120 :c:func:`PyLong_FromNativeBytes()` functions can be used to convert
121 a :c:type:`PyLongObject` to/from an array of bytes in base ``256``.
122
123
124 .. c:function:: PyObject* PyLong_FromUnicodeObject(PyObject *u, int base)
125
126 Convert a sequence of Unicode digits in the string *u* to a Python integer
127 value.
128
129 .. versionadded:: 3.3
130
131
132 .. c:function:: PyObject* PyLong_FromVoidPtr(void *p)
133
134 Create a Python integer from the pointer *p*. The pointer value can be
135 retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`.
136
137
138 .. c:function:: PyObject* PyLong_FromNativeBytes(const void* buffer, size_t n_bytes, int flags)
139
140 Create a Python integer from the value contained in the first *n_bytes* of
141 *buffer*, interpreted as a two's-complement signed number.
142
143 *flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will select
144 the native endian that CPython was compiled with and assume that the
145 most-significant bit is a sign bit. Passing
146 ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` will produce the same result as calling
147 :c:func:`PyLong_FromUnsignedNativeBytes`. Other flags are ignored.
148
149 .. versionadded:: 3.13
150
151
152 .. c:function:: PyObject* PyLong_FromUnsignedNativeBytes(const void* buffer, size_t n_bytes, int flags)
153
154 Create a Python integer from the value contained in the first *n_bytes* of
155 *buffer*, interpreted as an unsigned number.
156
157 *flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will select
158 the native endian that CPython was compiled with and assume that the
159 most-significant bit is not a sign bit. Flags other than endian are ignored.
160
161 .. versionadded:: 3.13
162
163
164 .. c:macro:: PyLong_FromPid(pid)
165
166 Macro for creating a Python integer from a process identifier.
167
168 This can be defined as an alias to :c:func:`PyLong_FromLong` or
169 :c:func:`PyLong_FromLongLong`, depending on the size of the system's
170 PID type.
171
172 .. versionadded:: 3.2
173
174
175 .. c:function:: long PyLong_AsLong(PyObject *obj)
176
177 .. index::
178 single: LONG_MAX (C macro)
179 single: OverflowError (built-in exception)
180
181 Return a C :c:expr:`long` representation of *obj*. If *obj* is not an
182 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method
183 (if present) to convert it to a :c:type:`PyLongObject`.
184
185 Raise :exc:`OverflowError` if the value of *obj* is out of range for a
186 :c:expr:`long`.
187
188 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
189
190 .. versionchanged:: 3.8
191 Use :meth:`~object.__index__` if available.
192
193 .. versionchanged:: 3.10
194 This function will no longer use :meth:`~object.__int__`.
195
196 .. c:namespace:: NULL
197
198 .. c:function:: long PyLong_AS_LONG(PyObject *obj)
199
200 Exactly equivalent to the preferred ``PyLong_AsLong``. In particular,
201 it can fail with :exc:`OverflowError` or another exception.
202
203 .. soft-deprecated:: 3.14
204
205 .. c:function:: int PyLong_AsInt(PyObject *obj)
206
207 Similar to :c:func:`PyLong_AsLong`, but store the result in a C
208 :c:expr:`int` instead of a C :c:expr:`long`.
209
210 .. versionadded:: 3.13
211
212
213 .. c:function:: long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)
214
215 Return a C :c:expr:`long` representation of *obj*. If *obj* is not an
216 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__`
217 method (if present) to convert it to a :c:type:`PyLongObject`.
218
219 If the value of *obj* is greater than :c:macro:`LONG_MAX` or less than
220 :c:macro:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and
221 return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception
222 occurs set *\*overflow* to ``0`` and return ``-1`` as usual.
223
224 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
225
226 .. versionchanged:: 3.8
227 Use :meth:`~object.__index__` if available.
228
229 .. versionchanged:: 3.10
230 This function will no longer use :meth:`~object.__int__`.
231
232
233 .. c:function:: long long PyLong_AsLongLong(PyObject *obj)
234
235 .. index::
236 single: OverflowError (built-in exception)
237
238 Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an
239 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method
240 (if present) to convert it to a :c:type:`PyLongObject`.
241
242 Raise :exc:`OverflowError` if the value of *obj* is out of range for a
243 :c:expr:`long long`.
244
245 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
246
247 .. versionchanged:: 3.8
248 Use :meth:`~object.__index__` if available.
249
250 .. versionchanged:: 3.10
251 This function will no longer use :meth:`~object.__int__`.
252
253
254 .. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
255
256 Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an
257 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method
258 (if present) to convert it to a :c:type:`PyLongObject`.
259
260 If the value of *obj* is greater than :c:macro:`LLONG_MAX` or less than
261 :c:macro:`LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively,
262 and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other
263 exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual.
264
265 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
266
267 .. versionadded:: 3.2
268
269 .. versionchanged:: 3.8
270 Use :meth:`~object.__index__` if available.
271
272 .. versionchanged:: 3.10
273 This function will no longer use :meth:`~object.__int__`.
274
275
276 .. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
277
278 .. index::
279 single: PY_SSIZE_T_MAX (C macro)
280 single: OverflowError (built-in exception)
281
282 Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must
283 be an instance of :c:type:`PyLongObject`.
284
285 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
286 :c:type:`Py_ssize_t`.
287
288 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
289
290
291 .. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
292
293 .. index::
294 single: ULONG_MAX (C macro)
295 single: OverflowError (built-in exception)
296
297 Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong*
298 must be an instance of :c:type:`PyLongObject`.
299
300 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
301 :c:expr:`unsigned long`.
302
303 Returns ``(unsigned long)-1`` on error.
304 Use :c:func:`PyErr_Occurred` to disambiguate.
305
306
307 .. c:function:: size_t PyLong_AsSize_t(PyObject *pylong)
308
309 .. index::
310 single: SIZE_MAX (C macro)
311 single: OverflowError (built-in exception)
312
313 Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be
314 an instance of :c:type:`PyLongObject`.
315
316 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
317 :c:type:`size_t`.
318
319 Returns ``(size_t)-1`` on error.
320 Use :c:func:`PyErr_Occurred` to disambiguate.
321
322
323 .. c:function:: unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
324
325 .. index::
326 single: OverflowError (built-in exception)
327
328 Return a C :c:expr:`unsigned long long` representation of *pylong*. *pylong*
329 must be an instance of :c:type:`PyLongObject`.
330
331 Raise :exc:`OverflowError` if the value of *pylong* is out of range for an
332 :c:expr:`unsigned long long`.
333
334 Returns ``(unsigned long long)-1`` on error.
335 Use :c:func:`PyErr_Occurred` to disambiguate.
336
337 .. versionchanged:: 3.1
338 A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`.
339
340
341 .. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)
342
343 Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not
344 an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__`
345 method (if present) to convert it to a :c:type:`PyLongObject`.
346
347 If the value of *obj* is out of range for an :c:expr:`unsigned long`,
348 return the reduction of that value modulo ``ULONG_MAX + 1``.
349
350 Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to
351 disambiguate.
352
353 .. versionchanged:: 3.8
354 Use :meth:`~object.__index__` if available.
355
356 .. versionchanged:: 3.10
357 This function will no longer use :meth:`~object.__int__`.
358
359
360 .. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)
361
362 Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj*
363 is not an instance of :c:type:`PyLongObject`, first call its
364 :meth:`~object.__index__` method (if present) to convert it to a
365 :c:type:`PyLongObject`.
366
367 If the value of *obj* is out of range for an :c:expr:`unsigned long long`,
368 return the reduction of that value modulo ``ULLONG_MAX + 1``.
369
370 Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred`
371 to disambiguate.
372
373 .. versionchanged:: 3.8
374 Use :meth:`~object.__index__` if available.
375
376 .. versionchanged:: 3.10
377 This function will no longer use :meth:`~object.__int__`.
378
379
380 .. c:function:: int PyLong_AsInt32(PyObject *obj, int32_t *value)
381 int PyLong_AsInt64(PyObject *obj, int64_t *value)
382
383 Set *\*value* to a signed C :c:expr:`int32_t` or :c:expr:`int64_t`
384 representation of *obj*.
385
386 If *obj* is not an instance of :c:type:`PyLongObject`, first call its
387 :meth:`~object.__index__` method (if present) to convert it to a
388 :c:type:`PyLongObject`.
389
390 If the *obj* value is out of range, raise an :exc:`OverflowError`.
391
392 Set *\*value* and return ``0`` on success.
393 Set an exception and return ``-1`` on error.
394
395 *value* must not be ``NULL``.
396
397 .. versionadded:: 3.14
398
399
400 .. c:function:: int PyLong_AsUInt32(PyObject *obj, uint32_t *value)
401 int PyLong_AsUInt64(PyObject *obj, uint64_t *value)
402
403 Set *\*value* to an unsigned C :c:expr:`uint32_t` or :c:expr:`uint64_t`
404 representation of *obj*.
405
406 If *obj* is not an instance of :c:type:`PyLongObject`, first call its
407 :meth:`~object.__index__` method (if present) to convert it to a
408 :c:type:`PyLongObject`.
409
410 * If *obj* is negative, raise a :exc:`ValueError`.
411 * If the *obj* value is out of range, raise an :exc:`OverflowError`.
412
413 Set *\*value* and return ``0`` on success.
414 Set an exception and return ``-1`` on error.
415
416 *value* must not be ``NULL``.
417
418 .. versionadded:: 3.14
419
420
421 .. c:function:: double PyLong_AsDouble(PyObject *pylong)
422
423 Return a C :c:expr:`double` representation of *pylong*. *pylong* must be
424 an instance of :c:type:`PyLongObject`.
425
426 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
427 :c:expr:`double`.
428
429 Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
430
431
432 .. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong)
433
434 Convert a Python integer *pylong* to a C :c:expr:`void` pointer.
435 If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This
436 is only assured to produce a usable :c:expr:`void` pointer for values created
437 with :c:func:`PyLong_FromVoidPtr`.
438
439 Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
440
441
442 .. c:function:: Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void* buffer, Py_ssize_t n_bytes, int flags)
443
444 Copy the Python integer value *pylong* to a native *buffer* of size
445 *n_bytes*. The *flags* can be set to ``-1`` to behave similarly to a C cast,
446 or to values documented below to control the behavior.
447
448 Returns ``-1`` with an exception raised on error. This may happen if
449 *pylong* cannot be interpreted as an integer, or if *pylong* was negative
450 and the ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` flag was set.
451
452 Otherwise, returns the number of bytes required to store the value.
453 If this is equal to or less than *n_bytes*, the entire value was copied.
454 All *n_bytes* of the buffer are written: remaining bytes filled by
455 copies of the sign bit.
456
457 If the returned value is greater than *n_bytes*, the value was
458 truncated: as many of the lowest bits of the value as could fit are written,
459 and the higher bits are ignored. This matches the typical behavior
460 of a C-style downcast.
461
462 .. note::
463
464 Overflow is not considered an error. If the returned value
465 is larger than *n_bytes*, most significant bits were discarded.
466
467 ``0`` will never be returned.
468
469 Values are always copied as two's-complement.
470
471 Usage example::
472
473 int32_t value;
474 Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1);
475 if (bytes < 0) {
476 // Failed. A Python exception was set with the reason.
477 return NULL;
478 }
479 else if (bytes <= (Py_ssize_t)sizeof(value)) {
480 // Success!
481 }
482 else {
483 // Overflow occurred, but 'value' contains the truncated
484 // lowest bits of pylong.
485 }
486
487 Passing zero to *n_bytes* will return the size of a buffer that would
488 be large enough to hold the value. This may be larger than technically
489 necessary, but not unreasonably so. If *n_bytes=0*, *buffer* may be
490 ``NULL``.
491
492 .. note::
493
494 Passing *n_bytes=0* to this function is not an accurate way to determine
495 the bit length of the value.
496
497 To get at the entire Python value of an unknown size, the function can be
498 called twice: first to determine the buffer size, then to fill it::
499
500 // Ask how much space we need.
501 Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1);
502 if (expected < 0) {
503 // Failed. A Python exception was set with the reason.
504 return NULL;
505 }
506 assert(expected != 0); // Impossible per the API definition.
507 uint8_t *bignum = malloc(expected);
508 if (!bignum) {
509 PyErr_SetString(PyExc_MemoryError, "bignum malloc failed.");
510 return NULL;
511 }
512 // Safely get the entire value.
513 Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1);
514 if (bytes < 0) { // Exception has been set.
515 free(bignum);
516 return NULL;
517 }
518 else if (bytes > expected) { // This should not be possible.
519 PyErr_SetString(PyExc_RuntimeError,
520 "Unexpected bignum truncation after a size check.");
521 free(bignum);
522 return NULL;
523 }
524 // The expected success given the above pre-check.
525 // ... use bignum ...
526 free(bignum);
527
528 *flags* is either ``-1`` (``Py_ASNATIVEBYTES_DEFAULTS``) to select defaults
529 that behave most like a C cast, or a combination of the other flags in
530 the table below.
531 Note that ``-1`` cannot be combined with other flags.
532
533 Currently, ``-1`` corresponds to
534 ``Py_ASNATIVEBYTES_NATIVE_ENDIAN | Py_ASNATIVEBYTES_UNSIGNED_BUFFER``.
535
536 .. c:namespace:: NULL
537
538 ============================================= ======
539 Flag Value
540 ============================================= ======
541 .. c:macro:: Py_ASNATIVEBYTES_DEFAULTS ``-1``
542 .. c:macro:: Py_ASNATIVEBYTES_BIG_ENDIAN ``0``
543 .. c:macro:: Py_ASNATIVEBYTES_LITTLE_ENDIAN ``1``
544 .. c:macro:: Py_ASNATIVEBYTES_NATIVE_ENDIAN ``3``
545 .. c:macro:: Py_ASNATIVEBYTES_UNSIGNED_BUFFER ``4``
546 .. c:macro:: Py_ASNATIVEBYTES_REJECT_NEGATIVE ``8``
547 .. c:macro:: Py_ASNATIVEBYTES_ALLOW_INDEX ``16``
548 ============================================= ======
549
550 Specifying ``Py_ASNATIVEBYTES_NATIVE_ENDIAN`` will override any other endian
551 flags. Passing ``2`` is reserved.
552
553 By default, sufficient buffer will be requested to include a sign bit.
554 For example, when converting 128 with *n_bytes=1*, the function will return
555 2 (or more) in order to store a zero sign bit.
556
557 If ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` is specified, a zero sign bit
558 will be omitted from size calculations. This allows, for example, 128 to fit
559 in a single-byte buffer. If the destination buffer is later treated as
560 signed, a positive input value may become negative.
561 Note that the flag does not affect handling of negative values: for those,
562 space for a sign bit is always requested.
563
564 Specifying ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` causes an exception to be set
565 if *pylong* is negative. Without this flag, negative values will be copied
566 provided there is enough space for at least one sign bit, regardless of
567 whether ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` was specified.
568
569 If ``Py_ASNATIVEBYTES_ALLOW_INDEX`` is specified and a non-integer value is
570 passed, its :meth:`~object.__index__` method will be called first. This may
571 result in Python code executing and other threads being allowed to run, which
572 could cause changes to other objects or values in use. When *flags* is
573 ``-1``, this option is not set, and non-integer values will raise
574 :exc:`TypeError`.
575
576 .. note::
577
578 With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without
579 *REJECT_NEGATIVE*), multiple Python integers can map to a single value
580 without overflow. For example, both ``255`` and ``-1`` fit a single-byte
581 buffer and set all its bits.
582 This matches typical C cast behavior.
583
584 .. versionadded:: 3.13
585
586
587 .. c:macro:: PyLong_AsPid(pid)
588
589 Macro for converting a Python integer into a process identifier.
590
591 This can be defined as an alias to :c:func:`PyLong_AsLong`,
592 :c:func:`PyLong_FromLongLong`, or :c:func:`PyLong_AsInt`, depending on the
593 size of the system's PID type.
594
595 .. versionadded:: 3.2
596
597
598 .. c:function:: int PyLong_GetSign(PyObject *obj, int *sign)
599
600 Get the sign of the integer object *obj*.
601
602 On success, set *\*sign* to the integer sign (0, -1 or +1 for zero, negative or
603 positive integer, respectively) and return 0.
604
605 On failure, return -1 with an exception set. This function always succeeds
606 if *obj* is a :c:type:`PyLongObject` or its subtype.
607
608 .. versionadded:: 3.14
609
610
611 .. c:function:: int PyLong_IsPositive(PyObject *obj)
612
613 Check if the integer object *obj* is positive (``obj > 0``).
614
615 If *obj* is an instance of :c:type:`PyLongObject` or its subtype,
616 return ``1`` when it's positive and ``0`` otherwise. Else set an
617 exception and return ``-1``.
618
619 .. versionadded:: 3.14
620
621
622 .. c:function:: int PyLong_IsNegative(PyObject *obj)
623
624 Check if the integer object *obj* is negative (``obj < 0``).
625
626 If *obj* is an instance of :c:type:`PyLongObject` or its subtype,
627 return ``1`` when it's negative and ``0`` otherwise. Else set an
628 exception and return ``-1``.
629
630 .. versionadded:: 3.14
631
632
633 .. c:function:: int PyLong_IsZero(PyObject *obj)
634
635 Check if the integer object *obj* is zero.
636
637 If *obj* is an instance of :c:type:`PyLongObject` or its subtype,
638 return ``1`` when it's zero and ``0`` otherwise. Else set an
639 exception and return ``-1``.
640
641 .. versionadded:: 3.14
642
643
644 .. c:function:: PyObject* PyLong_GetInfo(void)
645
646 On success, return a read only :term:`named tuple`, that holds
647 information about Python's internal representation of integers.
648 See :data:`sys.int_info` for description of individual fields.
649
650 On failure, return ``NULL`` with an exception set.
651
652 .. versionadded:: 3.1
653
654
655 .. c:function:: int PyUnstable_Long_IsCompact(const PyLongObject* op)
656
657 Return 1 if *op* is compact, 0 otherwise.
658
659 This function makes it possible for performance-critical code to implement
660 a “fast path” for small integers. For compact values use
661 :c:func:`PyUnstable_Long_CompactValue`; for others fall back to a
662 :c:func:`PyLong_As* <PyLong_AsSize_t>` function or
663 :c:func:`PyLong_AsNativeBytes`.
664
665 The speedup is expected to be negligible for most users.
666
667 Exactly what values are considered compact is an implementation detail
668 and is subject to change.
669
670 .. versionadded:: 3.12
671
672
673 .. c:function:: Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject* op)
674
675 If *op* is compact, as determined by :c:func:`PyUnstable_Long_IsCompact`,
676 return its value.
677
678 Otherwise, the return value is undefined.
679
680 .. versionadded:: 3.12
681
682
683 Export API
684 ^^^^^^^^^^
685
686 .. versionadded:: 3.14
687
688 .. c:struct:: PyLongLayout
689
690 Layout of an array of "digits" ("limbs" in the GMP terminology), used to
691 represent absolute value for arbitrary precision integers.
692
693 Use :c:func:`PyLong_GetNativeLayout` to get the native layout of Python
694 :class:`int` objects, used internally for integers with "big enough"
695 absolute value.
696
697 See also :data:`sys.int_info` which exposes similar information in Python.
698
699 .. c:member:: uint8_t bits_per_digit
700
701 Bits per digit. For example, a 15 bit digit means that bits 0-14 contain
702 meaningful information.
703
704 .. c:member:: uint8_t digit_size
705
706 Digit size in bytes. For example, a 15 bit digit will require at least 2
707 bytes.
708
709 .. c:member:: int8_t digits_order
710
711 Digits order:
712
713 - ``1`` for most significant digit first
714 - ``-1`` for least significant digit first
715
716 .. c:member:: int8_t digit_endianness
717
718 Digit endianness:
719
720 - ``1`` for most significant byte first (big endian)
721 - ``-1`` for least significant byte first (little endian)
722
723
724 .. c:function:: const PyLongLayout* PyLong_GetNativeLayout(void)
725
726 Get the native layout of Python :class:`int` objects.
727
728 See the :c:struct:`PyLongLayout` structure.
729
730 The function must not be called before Python initialization nor after
731 Python finalization. The returned layout is valid until Python is
732 finalized. The layout is the same for all Python sub-interpreters
733 in a process, and so it can be cached.
734
735
736 .. c:struct:: PyLongExport
737
738 Export of a Python :class:`int` object.
739
740 There are two cases:
741
742 * If :c:member:`digits` is ``NULL``, only use the :c:member:`value` member.
743 * If :c:member:`digits` is not ``NULL``, use :c:member:`negative`,
744 :c:member:`ndigits` and :c:member:`digits` members.
745
746 .. c:member:: int64_t value
747
748 The native integer value of the exported :class:`int` object.
749 Only valid if :c:member:`digits` is ``NULL``.
750
751 .. c:member:: uint8_t negative
752
753 ``1`` if the number is negative, ``0`` otherwise.
754 Only valid if :c:member:`digits` is not ``NULL``.
755
756 .. c:member:: Py_ssize_t ndigits
757
758 Number of digits in :c:member:`digits` array.
759 Only valid if :c:member:`digits` is not ``NULL``.
760
761 .. c:member:: const void *digits
762
763 Read-only array of unsigned digits. Can be ``NULL``.
764
765
766 .. c:function:: int PyLong_Export(PyObject *obj, PyLongExport *export_long)
767
768 Export a Python :class:`int` object.
769
770 *export_long* must point to a :c:struct:`PyLongExport` structure allocated
771 by the caller. It must not be ``NULL``.
772
773 On success, fill in *\*export_long* and return ``0``.
774 On error, set an exception and return ``-1``.
775
776 :c:func:`PyLong_FreeExport` must be called when the export is no longer
777 needed.
778
779 .. impl-detail::
780 This function always succeeds if *obj* is a Python :class:`int` object
781 or a subclass.
782
783
784 .. c:function:: void PyLong_FreeExport(PyLongExport *export_long)
785
786 Release the export *export_long* created by :c:func:`PyLong_Export`.
787
788 .. impl-detail::
789 Calling :c:func:`PyLong_FreeExport` is optional if *export_long->digits*
790 is ``NULL``.
791
792
793 PyLongWriter API
794 ^^^^^^^^^^^^^^^^
795
796 The :c:type:`PyLongWriter` API can be used to import an integer.
797
798 .. versionadded:: 3.14
799
800 .. c:struct:: PyLongWriter
801
802 A Python :class:`int` writer instance.
803
804 The instance must be destroyed by :c:func:`PyLongWriter_Finish` or
805 :c:func:`PyLongWriter_Discard`.
806
807
808 .. c:function:: PyLongWriter* PyLongWriter_Create(int negative, Py_ssize_t ndigits, void **digits)
809
810 Create a :c:type:`PyLongWriter`.
811
812 On success, allocate *\*digits* and return a writer.
813 On error, set an exception and return ``NULL``.
814
815 *negative* is ``1`` if the number is negative, or ``0`` otherwise.
816
817 *ndigits* is the number of digits in the *digits* array. It must be
818 greater than 0.
819
820 *digits* must not be NULL.
821
822 After a successful call to this function, the caller should fill in the
823 array of digits *digits* and then call :c:func:`PyLongWriter_Finish` to get
824 a Python :class:`int`.
825 The layout of *digits* is described by :c:func:`PyLong_GetNativeLayout`.
826
827 Digits must be in the range [``0``; ``(1 << bits_per_digit) - 1``]
828 (where the :c:struct:`~PyLongLayout.bits_per_digit` is the number of bits
829 per digit).
830 Any unused most significant digits must be set to ``0``.
831
832 Alternately, call :c:func:`PyLongWriter_Discard` to destroy the writer
833 instance without creating an :class:`~int` object.
834
835
836 .. c:function:: PyObject* PyLongWriter_Finish(PyLongWriter *writer)
837
838 Finish a :c:type:`PyLongWriter` created by :c:func:`PyLongWriter_Create`.
839
840 On success, return a Python :class:`int` object.
841 On error, set an exception and return ``NULL``.
842
843 The function takes care of normalizing the digits and converts the object
844 to a compact integer if needed.
845
846 The writer instance and the *digits* array are invalid after the call.
847
848
849 .. c:function:: void PyLongWriter_Discard(PyLongWriter *writer)
850
851 Discard a :c:type:`PyLongWriter` created by :c:func:`PyLongWriter_Create`.
852
853 If *writer* is ``NULL``, no operation is performed.
854
855 The writer instance and the *digits* array are invalid after the call.
856
857
858 Deprecated API
859 ^^^^^^^^^^^^^^
860
861 These macros are :term:`soft deprecated`. They describe parameters
862 of the internal representation of :c:type:`PyLongObject` instances.
863
864 Use :c:func:`PyLong_GetNativeLayout` instead, along with :c:func:`PyLong_Export`
865 to read integer data or :c:type:`PyLongWriter` to write it.
866 These currently use the same layout, but are designed to continue working correctly
867 even if CPython's internal integer representation changes.
868
869
870 .. c:macro:: PyLong_SHIFT
871
872 This is equivalent to :c:member:`~PyLongLayout.bits_per_digit` in
873 the output of :c:func:`PyLong_GetNativeLayout`.
874
875
876 .. c:macro:: PyLong_BASE
877
878 This is currently equivalent to :c:expr:`1 << PyLong_SHIFT`.
879
880
881 .. c:macro:: PyLong_MASK
882
883 This is currently equivalent to :c:expr:`(1 << PyLong_SHIFT) - 1`