Integer Objects¶
All integers are implemented as “long” integer objects of arbitrary size.
On error, mostPyLong_As* APIs return(returntype)-1 which cannot bedistinguished from a number. UsePyErr_Occurred() to disambiguate.
- typePyLongObject¶
- Part of theLimited API (as an opaque struct).
This subtype of
PyObjectrepresents a Python integer object.
- PyTypeObjectPyLong_Type¶
- Part of theStable ABI.
This instance of
PyTypeObjectrepresents the Python integer type.This is the same object asintin the Python layer.
- intPyLong_Check(PyObject*p)¶
Return true if its argument is a
PyLongObjector a subtype ofPyLongObject. This function always succeeds.
- intPyLong_CheckExact(PyObject*p)¶
Return true if its argument is a
PyLongObject, but not a subtype ofPyLongObject. This function always succeeds.
- PyObject*PyLong_FromLong(longv)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject fromv, orNULLon failure.CPython implementation detail: CPython keeps an array of integer objects for all integersbetween
-5and256. When you create an int in that rangeyou actually just get back a reference to the existing object.
- PyObject*PyLong_FromUnsignedLong(unsignedlongv)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject from a Cunsignedlong, orNULLon failure.
- PyObject*PyLong_FromSsize_t(Py_ssize_tv)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject from a CPy_ssize_t, orNULLon failure.
- PyObject*PyLong_FromSize_t(size_tv)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject from a Csize_t, orNULLon failure.
- PyObject*PyLong_FromLongLong(longlongv)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject from a Clonglong, orNULLon failure.
- PyObject*PyLong_FromUnsignedLongLong(unsignedlonglongv)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject from a Cunsignedlonglong,orNULLon failure.
- PyObject*PyLong_FromDouble(doublev)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectobject from the integer part ofv, orNULLon failure.
- PyObject*PyLong_FromString(constchar*str,char**pend,intbase)¶
- Return value: New reference. Part of theStable ABI.
Return a new
PyLongObjectbased on the string value instr, whichis interpreted according to the radix inbase, orNULLon failure. Ifpend is non-NULL,*pend will point to the end ofstr on success orto the first character that could not be processed on error. Ifbase is0,str is interpreted using theInteger literals definition; in this case, leadingzeros in a non-zero decimal number raises aValueError. Ifbase is not0, it must be between2and36, inclusive. Leading and trailingwhitespace and single underscores after a base specifier and between digits areignored. If there are no digits orstr is not NULL-terminated following thedigits and trailing whitespace,ValueErrorwill be raised.See also
Python methods
int.to_bytes()andint.from_bytes()to convert aPyLongObjectto/from an array of bytes in base256. You can call those from C usingPyObject_CallMethod().
- PyObject*PyLong_FromUnicodeObject(PyObject*u,intbase)¶
- Return value: New reference.
Convert a sequence of Unicode digits in the stringu to a Python integervalue.
Added in version 3.3.
- PyObject*PyLong_FromVoidPtr(void*p)¶
- Return value: New reference. Part of theStable ABI.
Create a Python integer from the pointerp. The pointer value can beretrieved from the resulting value using
PyLong_AsVoidPtr().
- PyObject*PyLong_FromNativeBytes(constvoid*buffer,size_tn_bytes,intflags)¶
Create a Python integer from the value contained in the firstn_bytes ofbuffer, interpreted as a two’s-complement signed number.
flags are as for
PyLong_AsNativeBytes(). Passing-1will selectthe native endian that CPython was compiled with and assume that themost-significant bit is a sign bit. PassingPy_ASNATIVEBYTES_UNSIGNED_BUFFERwill produce the same result as callingPyLong_FromUnsignedNativeBytes(). Other flags are ignored.Added in version 3.13.
- PyObject*PyLong_FromUnsignedNativeBytes(constvoid*buffer,size_tn_bytes,intflags)¶
Create a Python integer from the value contained in the firstn_bytes ofbuffer, interpreted as an unsigned number.
flags are as for
PyLong_AsNativeBytes(). Passing-1will selectthe native endian that CPython was compiled with and assume that themost-significant bit is not a sign bit. Flags other than endian are ignored.Added in version 3.13.
- PyLong_FromPid(pid)¶
Macro for creating a Python integer from a process identifier.
This can be defined as an alias to
PyLong_FromLong()orPyLong_FromLongLong(), depending on the size of the system’sPID type.Added in version 3.2.
- longPyLong_AsLong(PyObject*obj)¶
- Part of theStable ABI.
Return a Clong representation ofobj. Ifobj is not aninstance of
PyLongObject, first call its__index__()method(if present) to convert it to aPyLongObject.Raise
OverflowErrorif the value ofobj is out of range for along.Returns
-1on error. UsePyErr_Occurred()to disambiguate.Changed in version 3.8:Use
__index__()if available.Changed in version 3.10:This function will no longer use
__int__().- longPyLong_AS_LONG(PyObject*obj)¶
Asoft deprecated alias.Exactly equivalent to the preferred
PyLong_AsLong. In particular,it can fail withOverflowErroror another exception.Deprecated since version 3.14:The function is soft deprecated.
- longPyLong_AS_LONG(PyObject*obj)¶
- intPyLong_AsInt(PyObject*obj)¶
- Part of theStable ABI since version 3.13.
Similar to
PyLong_AsLong(), but store the result in a Cint instead of a Clong.Added in version 3.13.
- longPyLong_AsLongAndOverflow(PyObject*obj,int*overflow)¶
- Part of theStable ABI.
Return a Clong representation ofobj. Ifobj is not aninstance of
PyLongObject, first call its__index__()method (if present) to convert it to aPyLongObject.If the value ofobj is greater than
LONG_MAXor less thanLONG_MIN, set*overflow to1or-1, respectively, andreturn-1; otherwise, set*overflow to0. If any other exceptionoccurs set*overflow to0and return-1as usual.Returns
-1on error. UsePyErr_Occurred()to disambiguate.Changed in version 3.8:Use
__index__()if available.Changed in version 3.10:This function will no longer use
__int__().
- longlongPyLong_AsLongLong(PyObject*obj)¶
- Part of theStable ABI.
Return a Clonglong representation ofobj. Ifobj is not aninstance of
PyLongObject, first call its__index__()method(if present) to convert it to aPyLongObject.Raise
OverflowErrorif the value ofobj is out of range for alonglong.Returns
-1on error. UsePyErr_Occurred()to disambiguate.Changed in version 3.8:Use
__index__()if available.Changed in version 3.10:This function will no longer use
__int__().
- longlongPyLong_AsLongLongAndOverflow(PyObject*obj,int*overflow)¶
- Part of theStable ABI.
Return a Clonglong representation ofobj. Ifobj is not aninstance of
PyLongObject, first call its__index__()method(if present) to convert it to aPyLongObject.If the value ofobj is greater than
LLONG_MAXor less thanLLONG_MIN, set*overflow to1or-1, respectively,and return-1; otherwise, set*overflow to0. If any otherexception occurs set*overflow to0and return-1as usual.Returns
-1on error. UsePyErr_Occurred()to disambiguate.Added in version 3.2.
Changed in version 3.8:Use
__index__()if available.Changed in version 3.10:This function will no longer use
__int__().
- Py_ssize_tPyLong_AsSsize_t(PyObject*pylong)¶
- Part of theStable ABI.
Return a C
Py_ssize_trepresentation ofpylong.pylong mustbe an instance ofPyLongObject.Raise
OverflowErrorif the value ofpylong is out of range for aPy_ssize_t.Returns
-1on error. UsePyErr_Occurred()to disambiguate.
- unsignedlongPyLong_AsUnsignedLong(PyObject*pylong)¶
- Part of theStable ABI.
Return a Cunsignedlong representation ofpylong.pylongmust be an instance of
PyLongObject.Raise
OverflowErrorif the value ofpylong is out of range for aunsignedlong.Returns
(unsignedlong)-1on error.UsePyErr_Occurred()to disambiguate.
- size_tPyLong_AsSize_t(PyObject*pylong)¶
- Part of theStable ABI.
Return a C
size_trepresentation ofpylong.pylong must bean instance ofPyLongObject.Raise
OverflowErrorif the value ofpylong is out of range for asize_t.Returns
(size_t)-1on error.UsePyErr_Occurred()to disambiguate.
- unsignedlonglongPyLong_AsUnsignedLongLong(PyObject*pylong)¶
- Part of theStable ABI.
Return a Cunsignedlonglong representation ofpylong.pylongmust be an instance of
PyLongObject.Raise
OverflowErrorif the value ofpylong is out of range for anunsignedlonglong.Returns
(unsignedlonglong)-1on error.UsePyErr_Occurred()to disambiguate.Changed in version 3.1:A negativepylong now raises
OverflowError, notTypeError.
- unsignedlongPyLong_AsUnsignedLongMask(PyObject*obj)¶
- Part of theStable ABI.
Return a Cunsignedlong representation ofobj. Ifobj is notan instance of
PyLongObject, first call its__index__()method (if present) to convert it to aPyLongObject.If the value ofobj is out of range for anunsignedlong,return the reduction of that value modulo
ULONG_MAX+1.Returns
(unsignedlong)-1on error. UsePyErr_Occurred()todisambiguate.Changed in version 3.8:Use
__index__()if available.Changed in version 3.10:This function will no longer use
__int__().
- unsignedlonglongPyLong_AsUnsignedLongLongMask(PyObject*obj)¶
- Part of theStable ABI.
Return a Cunsignedlonglong representation ofobj. Ifobjis not an instance of
PyLongObject, first call its__index__()method (if present) to convert it to aPyLongObject.If the value ofobj is out of range for anunsignedlonglong,return the reduction of that value modulo
ULLONG_MAX+1.Returns
(unsignedlonglong)-1on error. UsePyErr_Occurred()to disambiguate.Changed in version 3.8:Use
__index__()if available.Changed in version 3.10:This function will no longer use
__int__().
- doublePyLong_AsDouble(PyObject*pylong)¶
- Part of theStable ABI.
Return a Cdouble representation ofpylong.pylong must bean instance of
PyLongObject.Raise
OverflowErrorif the value ofpylong is out of range for adouble.Returns
-1.0on error. UsePyErr_Occurred()to disambiguate.
- void*PyLong_AsVoidPtr(PyObject*pylong)¶
- Part of theStable ABI.
Convert a Python integerpylong to a Cvoid pointer.Ifpylong cannot be converted, an
OverflowErrorwill be raised. Thisis only assured to produce a usablevoid pointer for values createdwithPyLong_FromVoidPtr().Returns
NULLon error. UsePyErr_Occurred()to disambiguate.
- PyLong_AsPid(pid)¶
Macro for converting a Python integer into a process identifier.
This can be defined as an alias to
PyLong_AsLong(),PyLong_FromLongLong(), orPyLong_AsInt(), depending on thesize of the system’s PID type.Added in version 3.2.
- Py_ssize_tPyLong_AsNativeBytes(PyObject*pylong,void*buffer,Py_ssize_tn_bytes,intflags)¶
Copy the Python integer valuepylong to a nativebuffer of sizen_bytes. Theflags can be set to
-1to behave similarly to a C cast,or to values documented below to control the behavior.Returns
-1with an exception raised on error. This may happen ifpylong cannot be interpreted as an integer, or ifpylong was negativeand thePy_ASNATIVEBYTES_REJECT_NEGATIVEflag was set.Otherwise, returns the number of bytes required to store the value.If this is equal to or less thann_bytes, the entire value was copied.Alln_bytes of the buffer are written: large buffers are padded withzeroes.
If the returned value is greater thann_bytes, the value wastruncated: as many of the lowest bits of the value as could fit are written,and the higher bits are ignored. This matches the typical behaviorof a C-style downcast.
Note
Overflow is not considered an error. If the returned valueis larger thann_bytes, most significant bits were discarded.
0will never be returned.Values are always copied as two’s-complement.
Usage example:
int32_tvalue;Py_ssize_tbytes=PyLong_AsNativeBytes(pylong,&value,sizeof(value),-1);if(bytes<0){// Failed. A Python exception was set with the reason.returnNULL;}elseif(bytes<=(Py_ssize_t)sizeof(value)){// Success!}else{// Overflow occurred, but 'value' contains the truncated// lowest bits of pylong.}
Passing zero ton_bytes will return the size of a buffer that wouldbe large enough to hold the value. This may be larger than technicallynecessary, but not unreasonably so. Ifn_bytes=0,buffer may be
NULL.Note
Passingn_bytes=0 to this function is not an accurate way to determinethe bit length of the value.
To get at the entire Python value of an unknown size, the function can becalled twice: first to determine the buffer size, then to fill it:
// Ask how much space we need.Py_ssize_texpected=PyLong_AsNativeBytes(pylong,NULL,0,-1);if(expected<0){// Failed. A Python exception was set with the reason.returnNULL;}assert(expected!=0);// Impossible per the API definition.uint8_t*bignum=malloc(expected);if(!bignum){PyErr_SetString(PyExc_MemoryError,"bignum malloc failed.");returnNULL;}// Safely get the entire value.Py_ssize_tbytes=PyLong_AsNativeBytes(pylong,bignum,expected,-1);if(bytes<0){// Exception has been set.free(bignum);returnNULL;}elseif(bytes>expected){// This should not be possible.PyErr_SetString(PyExc_RuntimeError,"Unexpected bignum truncation after a size check.");free(bignum);returnNULL;}// The expected success given the above pre-check.// ... use bignum ...free(bignum);
flags is either
-1(Py_ASNATIVEBYTES_DEFAULTS) to select defaultsthat behave most like a C cast, or a combination of the other flags inthe table below.Note that-1cannot be combined with other flags.Currently,
-1corresponds toPy_ASNATIVEBYTES_NATIVE_ENDIAN|Py_ASNATIVEBYTES_UNSIGNED_BUFFER.Flag
Value
- Py_ASNATIVEBYTES_DEFAULTS¶
-1- Py_ASNATIVEBYTES_BIG_ENDIAN¶
0- Py_ASNATIVEBYTES_LITTLE_ENDIAN¶
1- Py_ASNATIVEBYTES_NATIVE_ENDIAN¶
3- Py_ASNATIVEBYTES_UNSIGNED_BUFFER¶
4- Py_ASNATIVEBYTES_REJECT_NEGATIVE¶
8- Py_ASNATIVEBYTES_ALLOW_INDEX¶
16Specifying
Py_ASNATIVEBYTES_NATIVE_ENDIANwill override any other endianflags. Passing2is reserved.By default, sufficient buffer will be requested to include a sign bit.For example, when converting 128 withn_bytes=1, the function will return2 (or more) in order to store a zero sign bit.
If
Py_ASNATIVEBYTES_UNSIGNED_BUFFERis specified, a zero sign bitwill be omitted from size calculations. This allows, for example, 128 to fitin a single-byte buffer. If the destination buffer is later treated assigned, a positive input value may become negative.Note that the flag does not affect handling of negative values: for those,space for a sign bit is always requested.Specifying
Py_ASNATIVEBYTES_REJECT_NEGATIVEcauses an exception to be setifpylong is negative. Without this flag, negative values will be copiedprovided there is enough space for at least one sign bit, regardless ofwhetherPy_ASNATIVEBYTES_UNSIGNED_BUFFERwas specified.If
Py_ASNATIVEBYTES_ALLOW_INDEXis specified and a non-integer value ispassed, its__index__()method will be called first. This mayresult in Python code executing and other threads being allowed to run, whichcould cause changes to other objects or values in use. Whenflags is-1, this option is not set, and non-integer values will raiseTypeError.Note
With the defaultflags (
-1, orUNSIGNED_BUFFER withoutREJECT_NEGATIVE), multiple Python integers can map to a single valuewithout overflow. For example, both255and-1fit a single-bytebuffer and set all its bits.This matches typical C cast behavior.Added in version 3.13.
- Py_ASNATIVEBYTES_DEFAULTS¶
- PyObject*PyLong_GetInfo(void)¶
- Part of theStable ABI.
On success, return a read onlynamed tuple, that holdsinformation about Python’s internal representation of integers.See
sys.int_infofor description of individual fields.On failure, return
NULLwith an exception set.Added in version 3.1.
- intPyUnstable_Long_IsCompact(constPyLongObject*op)¶
- This isUnstable API. It may change without warning in minor releases.
Return 1 ifop is compact, 0 otherwise.
This function makes it possible for performance-critical code to implementa “fast path” for small integers. For compact values use
PyUnstable_Long_CompactValue(); for others fall back to aPyLong_As*function orPyLong_AsNativeBytes().The speedup is expected to be negligible for most users.
Exactly what values are considered compact is an implementation detailand is subject to change.
Added in version 3.12.
- Py_ssize_tPyUnstable_Long_CompactValue(constPyLongObject*op)¶
- This isUnstable API. It may change without warning in minor releases.
Ifop is compact, as determined by
PyUnstable_Long_IsCompact(),return its value.Otherwise, the return value is undefined.
Added in version 3.12.