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_FromDouble(double v)
81
82 Return a new :c:type:`PyLongObject` object from the integer part of *v*, or
83 ``NULL`` on failure.
84
85
86 .. c:function:: PyObject* PyLong_FromString(const char *str, char **pend, int base)
87
88 Return a new :c:type:`PyLongObject` based on the string value in *str*, which
89 is interpreted according to the radix in *base*, or ``NULL`` on failure. If
90 *pend* is non-``NULL``, *\*pend* will point to the end of *str* on success or
91 to the first character that could not be processed on error. If *base* is ``0``,
92 *str* is interpreted using the :ref:`integers` definition; in this case, leading
93 zeros in a non-zero decimal number raises a :exc:`ValueError`. If *base* is not
94 ``0``, it must be between ``2`` and ``36``, inclusive. Leading and trailing
95 whitespace and single underscores after a base specifier and between digits are
96 ignored. If there are no digits or *str* is not NULL-terminated following the
97 digits and trailing whitespace, :exc:`ValueError` will be raised.
98
99 .. seealso:: Python methods :meth:`int.to_bytes` and :meth:`int.from_bytes`
100 to convert a :c:type:`PyLongObject` to/from an array of bytes in base
101 ``256``. You can call those from C using :c:func:`PyObject_CallMethod`.
102
103
104 .. c:function:: PyObject* PyLong_FromUnicodeObject(PyObject *u, int base)
105
106 Convert a sequence of Unicode digits in the string *u* to a Python integer
107 value.
108
109 .. versionadded:: 3.3
110
111
112 .. c:function:: PyObject* PyLong_FromVoidPtr(void *p)
113
114 Create a Python integer from the pointer *p*. The pointer value can be
115 retrieved from the resulting value using :c:func:`PyLong_AsVoidPtr`.
116
117
118 .. c:function:: PyObject* PyLong_FromNativeBytes(const void* buffer, size_t n_bytes, int flags)
119
120 Create a Python integer from the value contained in the first *n_bytes* of
121 *buffer*, interpreted as a two's-complement signed number.
122
123 *flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will select
124 the native endian that CPython was compiled with and assume that the
125 most-significant bit is a sign bit. Passing
126 ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` will produce the same result as calling
127 :c:func:`PyLong_FromUnsignedNativeBytes`. Other flags are ignored.
128
129 .. versionadded:: 3.13
130
131
132 .. c:function:: PyObject* PyLong_FromUnsignedNativeBytes(const void* buffer, size_t n_bytes, int flags)
133
134 Create a Python integer from the value contained in the first *n_bytes* of
135 *buffer*, interpreted as an unsigned number.
136
137 *flags* are as for :c:func:`PyLong_AsNativeBytes`. Passing ``-1`` will select
138 the native endian that CPython was compiled with and assume that the
139 most-significant bit is not a sign bit. Flags other than endian are ignored.
140
141 .. versionadded:: 3.13
142
143
144 .. c:macro:: PyLong_FromPid(pid)
145
146 Macro for creating a Python integer from a process identifier.
147
148 This can be defined as an alias to :c:func:`PyLong_FromLong` or
149 :c:func:`PyLong_FromLongLong`, depending on the size of the system's
150 PID type.
151
152 .. versionadded:: 3.2
153
154
155 .. c:function:: long PyLong_AsLong(PyObject *obj)
156
157 .. index::
158 single: LONG_MAX (C macro)
159 single: OverflowError (built-in exception)
160
161 Return a C :c:expr:`long` representation of *obj*. If *obj* is not an
162 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method
163 (if present) to convert it to a :c:type:`PyLongObject`.
164
165 Raise :exc:`OverflowError` if the value of *obj* is out of range for a
166 :c:expr:`long`.
167
168 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
169
170 .. versionchanged:: 3.8
171 Use :meth:`~object.__index__` if available.
172
173 .. versionchanged:: 3.10
174 This function will no longer use :meth:`~object.__int__`.
175
176 .. c:namespace:: NULL
177
178 .. c:function:: long PyLong_AS_LONG(PyObject *obj)
179
180 A :term:`soft deprecated` alias.
181 Exactly equivalent to the preferred ``PyLong_AsLong``. In particular,
182 it can fail with :exc:`OverflowError` or another exception.
183
184 .. deprecated:: 3.14
185 The function is soft deprecated.
186
187 .. c:function:: int PyLong_AsInt(PyObject *obj)
188
189 Similar to :c:func:`PyLong_AsLong`, but store the result in a C
190 :c:expr:`int` instead of a C :c:expr:`long`.
191
192 .. versionadded:: 3.13
193
194
195 .. c:function:: long PyLong_AsLongAndOverflow(PyObject *obj, int *overflow)
196
197 Return a C :c:expr:`long` representation of *obj*. If *obj* is not an
198 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__`
199 method (if present) to convert it to a :c:type:`PyLongObject`.
200
201 If the value of *obj* is greater than :c:macro:`LONG_MAX` or less than
202 :c:macro:`LONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively, and
203 return ``-1``; otherwise, set *\*overflow* to ``0``. If any other exception
204 occurs set *\*overflow* to ``0`` and return ``-1`` as usual.
205
206 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
207
208 .. versionchanged:: 3.8
209 Use :meth:`~object.__index__` if available.
210
211 .. versionchanged:: 3.10
212 This function will no longer use :meth:`~object.__int__`.
213
214
215 .. c:function:: long long PyLong_AsLongLong(PyObject *obj)
216
217 .. index::
218 single: OverflowError (built-in exception)
219
220 Return a C :c:expr:`long long` representation of *obj*. If *obj* is not an
221 instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__` method
222 (if present) to convert it to a :c:type:`PyLongObject`.
223
224 Raise :exc:`OverflowError` if the value of *obj* is out of range for a
225 :c:expr:`long long`.
226
227 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
228
229 .. versionchanged:: 3.8
230 Use :meth:`~object.__index__` if available.
231
232 .. versionchanged:: 3.10
233 This function will no longer use :meth:`~object.__int__`.
234
235
236 .. c:function:: long long PyLong_AsLongLongAndOverflow(PyObject *obj, int *overflow)
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 If the value of *obj* is greater than :c:macro:`LLONG_MAX` or less than
243 :c:macro:`LLONG_MIN`, set *\*overflow* to ``1`` or ``-1``, respectively,
244 and return ``-1``; otherwise, set *\*overflow* to ``0``. If any other
245 exception occurs set *\*overflow* to ``0`` and return ``-1`` as usual.
246
247 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
248
249 .. versionadded:: 3.2
250
251 .. versionchanged:: 3.8
252 Use :meth:`~object.__index__` if available.
253
254 .. versionchanged:: 3.10
255 This function will no longer use :meth:`~object.__int__`.
256
257
258 .. c:function:: Py_ssize_t PyLong_AsSsize_t(PyObject *pylong)
259
260 .. index::
261 single: PY_SSIZE_T_MAX (C macro)
262 single: OverflowError (built-in exception)
263
264 Return a C :c:type:`Py_ssize_t` representation of *pylong*. *pylong* must
265 be an instance of :c:type:`PyLongObject`.
266
267 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
268 :c:type:`Py_ssize_t`.
269
270 Returns ``-1`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
271
272
273 .. c:function:: unsigned long PyLong_AsUnsignedLong(PyObject *pylong)
274
275 .. index::
276 single: ULONG_MAX (C macro)
277 single: OverflowError (built-in exception)
278
279 Return a C :c:expr:`unsigned long` representation of *pylong*. *pylong*
280 must be an instance of :c:type:`PyLongObject`.
281
282 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
283 :c:expr:`unsigned long`.
284
285 Returns ``(unsigned long)-1`` on error.
286 Use :c:func:`PyErr_Occurred` to disambiguate.
287
288
289 .. c:function:: size_t PyLong_AsSize_t(PyObject *pylong)
290
291 .. index::
292 single: SIZE_MAX (C macro)
293 single: OverflowError (built-in exception)
294
295 Return a C :c:type:`size_t` representation of *pylong*. *pylong* must be
296 an instance of :c:type:`PyLongObject`.
297
298 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
299 :c:type:`size_t`.
300
301 Returns ``(size_t)-1`` on error.
302 Use :c:func:`PyErr_Occurred` to disambiguate.
303
304
305 .. c:function:: unsigned long long PyLong_AsUnsignedLongLong(PyObject *pylong)
306
307 .. index::
308 single: OverflowError (built-in exception)
309
310 Return a C :c:expr:`unsigned long long` representation of *pylong*. *pylong*
311 must be an instance of :c:type:`PyLongObject`.
312
313 Raise :exc:`OverflowError` if the value of *pylong* is out of range for an
314 :c:expr:`unsigned long long`.
315
316 Returns ``(unsigned long long)-1`` on error.
317 Use :c:func:`PyErr_Occurred` to disambiguate.
318
319 .. versionchanged:: 3.1
320 A negative *pylong* now raises :exc:`OverflowError`, not :exc:`TypeError`.
321
322
323 .. c:function:: unsigned long PyLong_AsUnsignedLongMask(PyObject *obj)
324
325 Return a C :c:expr:`unsigned long` representation of *obj*. If *obj* is not
326 an instance of :c:type:`PyLongObject`, first call its :meth:`~object.__index__`
327 method (if present) to convert it to a :c:type:`PyLongObject`.
328
329 If the value of *obj* is out of range for an :c:expr:`unsigned long`,
330 return the reduction of that value modulo ``ULONG_MAX + 1``.
331
332 Returns ``(unsigned long)-1`` on error. Use :c:func:`PyErr_Occurred` to
333 disambiguate.
334
335 .. versionchanged:: 3.8
336 Use :meth:`~object.__index__` if available.
337
338 .. versionchanged:: 3.10
339 This function will no longer use :meth:`~object.__int__`.
340
341
342 .. c:function:: unsigned long long PyLong_AsUnsignedLongLongMask(PyObject *obj)
343
344 Return a C :c:expr:`unsigned long long` representation of *obj*. If *obj*
345 is not an instance of :c:type:`PyLongObject`, first call its
346 :meth:`~object.__index__` method (if present) to convert it to a
347 :c:type:`PyLongObject`.
348
349 If the value of *obj* is out of range for an :c:expr:`unsigned long long`,
350 return the reduction of that value modulo ``ULLONG_MAX + 1``.
351
352 Returns ``(unsigned long long)-1`` on error. Use :c:func:`PyErr_Occurred`
353 to disambiguate.
354
355 .. versionchanged:: 3.8
356 Use :meth:`~object.__index__` if available.
357
358 .. versionchanged:: 3.10
359 This function will no longer use :meth:`~object.__int__`.
360
361
362 .. c:function:: double PyLong_AsDouble(PyObject *pylong)
363
364 Return a C :c:expr:`double` representation of *pylong*. *pylong* must be
365 an instance of :c:type:`PyLongObject`.
366
367 Raise :exc:`OverflowError` if the value of *pylong* is out of range for a
368 :c:expr:`double`.
369
370 Returns ``-1.0`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
371
372
373 .. c:function:: void* PyLong_AsVoidPtr(PyObject *pylong)
374
375 Convert a Python integer *pylong* to a C :c:expr:`void` pointer.
376 If *pylong* cannot be converted, an :exc:`OverflowError` will be raised. This
377 is only assured to produce a usable :c:expr:`void` pointer for values created
378 with :c:func:`PyLong_FromVoidPtr`.
379
380 Returns ``NULL`` on error. Use :c:func:`PyErr_Occurred` to disambiguate.
381
382
383 .. c:macro:: PyLong_AsPid(pid)
384
385 Macro for converting a Python integer into a process identifier.
386
387 This can be defined as an alias to :c:func:`PyLong_AsLong`,
388 :c:func:`PyLong_FromLongLong`, or :c:func:`PyLong_AsInt`, depending on the
389 size of the system's PID type.
390
391 .. versionadded:: 3.2
392
393
394 .. c:function:: Py_ssize_t PyLong_AsNativeBytes(PyObject *pylong, void* buffer, Py_ssize_t n_bytes, int flags)
395
396 Copy the Python integer value *pylong* to a native *buffer* of size
397 *n_bytes*. The *flags* can be set to ``-1`` to behave similarly to a C cast,
398 or to values documented below to control the behavior.
399
400 Returns ``-1`` with an exception raised on error. This may happen if
401 *pylong* cannot be interpreted as an integer, or if *pylong* was negative
402 and the ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` flag was set.
403
404 Otherwise, returns the number of bytes required to store the value.
405 If this is equal to or less than *n_bytes*, the entire value was copied.
406 All *n_bytes* of the buffer are written: remaining bytes filled by
407 copies of the sign bit.
408
409 If the returned value is greater than *n_bytes*, the value was
410 truncated: as many of the lowest bits of the value as could fit are written,
411 and the higher bits are ignored. This matches the typical behavior
412 of a C-style downcast.
413
414 .. note::
415
416 Overflow is not considered an error. If the returned value
417 is larger than *n_bytes*, most significant bits were discarded.
418
419 ``0`` will never be returned.
420
421 Values are always copied as two's-complement.
422
423 Usage example::
424
425 int32_t value;
426 Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, &value, sizeof(value), -1);
427 if (bytes < 0) {
428 // Failed. A Python exception was set with the reason.
429 return NULL;
430 }
431 else if (bytes <= (Py_ssize_t)sizeof(value)) {
432 // Success!
433 }
434 else {
435 // Overflow occurred, but 'value' contains the truncated
436 // lowest bits of pylong.
437 }
438
439 Passing zero to *n_bytes* will return the size of a buffer that would
440 be large enough to hold the value. This may be larger than technically
441 necessary, but not unreasonably so. If *n_bytes=0*, *buffer* may be
442 ``NULL``.
443
444 .. note::
445
446 Passing *n_bytes=0* to this function is not an accurate way to determine
447 the bit length of the value.
448
449 To get at the entire Python value of an unknown size, the function can be
450 called twice: first to determine the buffer size, then to fill it::
451
452 // Ask how much space we need.
453 Py_ssize_t expected = PyLong_AsNativeBytes(pylong, NULL, 0, -1);
454 if (expected < 0) {
455 // Failed. A Python exception was set with the reason.
456 return NULL;
457 }
458 assert(expected != 0); // Impossible per the API definition.
459 uint8_t *bignum = malloc(expected);
460 if (!bignum) {
461 PyErr_SetString(PyExc_MemoryError, "bignum malloc failed.");
462 return NULL;
463 }
464 // Safely get the entire value.
465 Py_ssize_t bytes = PyLong_AsNativeBytes(pylong, bignum, expected, -1);
466 if (bytes < 0) { // Exception has been set.
467 free(bignum);
468 return NULL;
469 }
470 else if (bytes > expected) { // This should not be possible.
471 PyErr_SetString(PyExc_RuntimeError,
472 "Unexpected bignum truncation after a size check.");
473 free(bignum);
474 return NULL;
475 }
476 // The expected success given the above pre-check.
477 // ... use bignum ...
478 free(bignum);
479
480 *flags* is either ``-1`` (``Py_ASNATIVEBYTES_DEFAULTS``) to select defaults
481 that behave most like a C cast, or a combination of the other flags in
482 the table below.
483 Note that ``-1`` cannot be combined with other flags.
484
485 Currently, ``-1`` corresponds to
486 ``Py_ASNATIVEBYTES_NATIVE_ENDIAN | Py_ASNATIVEBYTES_UNSIGNED_BUFFER``.
487
488 .. c:namespace:: NULL
489
490 ============================================= ======
491 Flag Value
492 ============================================= ======
493 .. c:macro:: Py_ASNATIVEBYTES_DEFAULTS ``-1``
494 .. c:macro:: Py_ASNATIVEBYTES_BIG_ENDIAN ``0``
495 .. c:macro:: Py_ASNATIVEBYTES_LITTLE_ENDIAN ``1``
496 .. c:macro:: Py_ASNATIVEBYTES_NATIVE_ENDIAN ``3``
497 .. c:macro:: Py_ASNATIVEBYTES_UNSIGNED_BUFFER ``4``
498 .. c:macro:: Py_ASNATIVEBYTES_REJECT_NEGATIVE ``8``
499 .. c:macro:: Py_ASNATIVEBYTES_ALLOW_INDEX ``16``
500 ============================================= ======
501
502 Specifying ``Py_ASNATIVEBYTES_NATIVE_ENDIAN`` will override any other endian
503 flags. Passing ``2`` is reserved.
504
505 By default, sufficient buffer will be requested to include a sign bit.
506 For example, when converting 128 with *n_bytes=1*, the function will return
507 2 (or more) in order to store a zero sign bit.
508
509 If ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` is specified, a zero sign bit
510 will be omitted from size calculations. This allows, for example, 128 to fit
511 in a single-byte buffer. If the destination buffer is later treated as
512 signed, a positive input value may become negative.
513 Note that the flag does not affect handling of negative values: for those,
514 space for a sign bit is always requested.
515
516 Specifying ``Py_ASNATIVEBYTES_REJECT_NEGATIVE`` causes an exception to be set
517 if *pylong* is negative. Without this flag, negative values will be copied
518 provided there is enough space for at least one sign bit, regardless of
519 whether ``Py_ASNATIVEBYTES_UNSIGNED_BUFFER`` was specified.
520
521 If ``Py_ASNATIVEBYTES_ALLOW_INDEX`` is specified and a non-integer value is
522 passed, its :meth:`~object.__index__` method will be called first. This may
523 result in Python code executing and other threads being allowed to run, which
524 could cause changes to other objects or values in use. When *flags* is
525 ``-1``, this option is not set, and non-integer values will raise
526 :exc:`TypeError`.
527
528 .. note::
529
530 With the default *flags* (``-1``, or *UNSIGNED_BUFFER* without
531 *REJECT_NEGATIVE*), multiple Python integers can map to a single value
532 without overflow. For example, both ``255`` and ``-1`` fit a single-byte
533 buffer and set all its bits.
534 This matches typical C cast behavior.
535
536 .. versionadded:: 3.13
537
538
539 .. c:function:: PyObject* PyLong_GetInfo(void)
540
541 On success, return a read only :term:`named tuple`, that holds
542 information about Python's internal representation of integers.
543 See :data:`sys.int_info` for description of individual fields.
544
545 On failure, return ``NULL`` with an exception set.
546
547 .. versionadded:: 3.1
548
549
550 .. c:function:: int PyUnstable_Long_IsCompact(const PyLongObject* op)
551
552 Return 1 if *op* is compact, 0 otherwise.
553
554 This function makes it possible for performance-critical code to implement
555 a “fast path” for small integers. For compact values use
556 :c:func:`PyUnstable_Long_CompactValue`; for others fall back to a
557 :c:func:`PyLong_As* <PyLong_AsSize_t>` function or
558 :c:func:`PyLong_AsNativeBytes`.
559
560 The speedup is expected to be negligible for most users.
561
562 Exactly what values are considered compact is an implementation detail
563 and is subject to change.
564
565 .. versionadded:: 3.12
566
567
568 .. c:function:: Py_ssize_t PyUnstable_Long_CompactValue(const PyLongObject* op)
569
570 If *op* is compact, as determined by :c:func:`PyUnstable_Long_IsCompact`,
571 return its value.
572
573 Otherwise, the return value is undefined.
574
575 .. versionadded:: 3.12
576