整數物件¶
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¶
- 為受限 API 的一部分 (做為一個不透明結構 (opaque struct)).
This subtype of
PyObject
represents a Python integer object.
- PyTypeObjectPyLong_Type¶
- 為穩定 ABI 的一部分.
This instance of
PyTypeObject
represents the Python integer type.This is the same object asint
in the Python layer.
- intPyLong_Check(PyObject*p)¶
Return true if its argument is a
PyLongObject
or 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)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object fromv, orNULL
on failure.CPython 實作細節: CPython keeps an array of integer objects for all integersbetween
-5
and256
. When you create an int in that rangeyou actually just get back a reference to the existing object.
- PyObject*PyLong_FromUnsignedLong(unsignedlongv)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object from a Cunsignedlong, orNULL
on failure.
- PyObject*PyLong_FromSsize_t(Py_ssize_tv)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object from a CPy_ssize_t
, orNULL
on failure.
- PyObject*PyLong_FromSize_t(size_tv)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object from a Csize_t
, orNULL
on failure.
- PyObject*PyLong_FromLongLong(longlongv)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object from a Clonglong, orNULL
on failure.
- PyObject*PyLong_FromInt32(int32_tvalue)¶
- PyObject*PyLong_FromInt64(int64_tvalue)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
Return a new
PyLongObject
object from a signed Cint32_t orint64_t, orNULL
with an exception set on failure.在 3.14 版被加入.
- PyObject*PyLong_FromUnsignedLongLong(unsignedlonglongv)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object from a Cunsignedlonglong,orNULL
on failure.
- PyObject*PyLong_FromUInt32(uint32_tvalue)¶
- PyObject*PyLong_FromUInt64(uint64_tvalue)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
Return a new
PyLongObject
object from an unsigned Cuint32_t oruint64_t, orNULL
with an exception set on failure.在 3.14 版被加入.
- PyObject*PyLong_FromDouble(doublev)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
object from the integer part ofv, orNULL
on failure.
- PyObject*PyLong_FromString(constchar*str,char**pend,intbase)¶
- 回傳值:新的參照。 為穩定 ABI 的一部分.
Return a new
PyLongObject
based on the string value instr, whichis interpreted according to the radix inbase, orNULL
on 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 between2
and36
, 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,ValueError
will be raised.也參考
PyLong_AsNativeBytes()
andPyLong_FromNativeBytes()
functions can be used to convertaPyLongObject
to/from an array of bytes in base256
.
- PyObject*PyLong_FromUnicodeObject(PyObject*u,intbase)¶
- 回傳值:新的參照。
Convert a sequence of Unicode digits in the stringu to a Python integervalue.
在 3.3 版被加入.
- PyObject*PyLong_FromVoidPtr(void*p)¶
- 回傳值:新的參照。 為穩定 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)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
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-1
will selectthe native endian that CPython was compiled with and assume that themost-significant bit is a sign bit. PassingPy_ASNATIVEBYTES_UNSIGNED_BUFFER
will produce the same result as callingPyLong_FromUnsignedNativeBytes()
. Other flags are ignored.在 3.13 版被加入.
- PyObject*PyLong_FromUnsignedNativeBytes(constvoid*buffer,size_tn_bytes,intflags)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
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-1
will 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.在 3.13 版被加入.
- longPyLong_AsLong(PyObject*obj)¶
- 為穩定 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
OverflowError
if the value ofobj is out of range for along.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.在 3.8 版的變更:Use
__index__()
if available.在 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 withOverflowError
or another exception.在 3.14 版之後被棄用:The function is soft deprecated.
- longPyLong_AS_LONG(PyObject*obj)¶
- intPyLong_AsInt(PyObject*obj)¶
- 為穩定 ABI 的一部分 自 3.13 版本開始.
Similar to
PyLong_AsLong()
, but store the result in a Cint instead of a Clong.在 3.13 版被加入.
- longPyLong_AsLongAndOverflow(PyObject*obj,int*overflow)¶
- 為穩定 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_MAX
or less thanLONG_MIN
, set*overflow to1
or-1
, respectively, andreturn-1
; otherwise, set*overflow to0
. If any other exceptionoccurs set*overflow to0
and return-1
as usual.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.在 3.8 版的變更:Use
__index__()
if available.在 3.10 版的變更:This function will no longer use
__int__()
.
- longlongPyLong_AsLongLong(PyObject*obj)¶
- 為穩定 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
OverflowError
if the value ofobj is out of range for alonglong.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.在 3.8 版的變更:Use
__index__()
if available.在 3.10 版的變更:This function will no longer use
__int__()
.
- longlongPyLong_AsLongLongAndOverflow(PyObject*obj,int*overflow)¶
- 為穩定 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_MAX
or less thanLLONG_MIN
, set*overflow to1
or-1
, respectively,and return-1
; otherwise, set*overflow to0
. If any otherexception occurs set*overflow to0
and return-1
as usual.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.在 3.2 版被加入.
在 3.8 版的變更:Use
__index__()
if available.在 3.10 版的變更:This function will no longer use
__int__()
.
- Py_ssize_tPyLong_AsSsize_t(PyObject*pylong)¶
- 為穩定 ABI 的一部分.
Return a C
Py_ssize_t
representation ofpylong.pylong mustbe an instance ofPyLongObject
.Raise
OverflowError
if the value ofpylong is out of range for aPy_ssize_t
.Returns
-1
on error. UsePyErr_Occurred()
to disambiguate.
- unsignedlongPyLong_AsUnsignedLong(PyObject*pylong)¶
- 為穩定 ABI 的一部分.
Return a Cunsignedlong representation ofpylong.pylongmust be an instance of
PyLongObject
.Raise
OverflowError
if the value ofpylong is out of range for aunsignedlong.Returns
(unsignedlong)-1
on error.UsePyErr_Occurred()
to disambiguate.
- size_tPyLong_AsSize_t(PyObject*pylong)¶
- 為穩定 ABI 的一部分.
Return a C
size_t
representation ofpylong.pylong must bean instance ofPyLongObject
.Raise
OverflowError
if the value ofpylong is out of range for asize_t
.Returns
(size_t)-1
on error.UsePyErr_Occurred()
to disambiguate.
- unsignedlonglongPyLong_AsUnsignedLongLong(PyObject*pylong)¶
- 為穩定 ABI 的一部分.
Return a Cunsignedlonglong representation ofpylong.pylongmust be an instance of
PyLongObject
.Raise
OverflowError
if the value ofpylong is out of range for anunsignedlonglong.Returns
(unsignedlonglong)-1
on error.UsePyErr_Occurred()
to disambiguate.在 3.1 版的變更:A negativepylong now raises
OverflowError
, notTypeError
.
- unsignedlongPyLong_AsUnsignedLongMask(PyObject*obj)¶
- 為穩定 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)-1
on error. UsePyErr_Occurred()
todisambiguate.在 3.8 版的變更:Use
__index__()
if available.在 3.10 版的變更:This function will no longer use
__int__()
.
- unsignedlonglongPyLong_AsUnsignedLongLongMask(PyObject*obj)¶
- 為穩定 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)-1
on error. UsePyErr_Occurred()
to disambiguate.在 3.8 版的變更:Use
__index__()
if available.在 3.10 版的變更:This function will no longer use
__int__()
.
- intPyLong_AsInt32(PyObject*obj,int32_t*value)¶
- intPyLong_AsInt64(PyObject*obj,int64_t*value)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
Set*value to a signed Cint32_t orint64_trepresentation ofobj.
Ifobj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.If theobj value is out of range, raise an
OverflowError
.Set*value and return
0
on success.Set an exception and return-1
on error.value must not be
NULL
.在 3.14 版被加入.
- intPyLong_AsUInt32(PyObject*obj,uint32_t*value)¶
- intPyLong_AsUInt64(PyObject*obj,uint64_t*value)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
Set*value to an unsigned Cuint32_t oruint64_trepresentation ofobj.
Ifobj is not an instance of
PyLongObject
, first call its__index__()
method (if present) to convert it to aPyLongObject
.Ifobj is negative, raise a
ValueError
.If theobj value is out of range, raise an
OverflowError
.
Set*value and return
0
on success.Set an exception and return-1
on error.value must not be
NULL
.在 3.14 版被加入.
- doublePyLong_AsDouble(PyObject*pylong)¶
- 為穩定 ABI 的一部分.
Return a Cdouble representation ofpylong.pylong must bean instance of
PyLongObject
.Raise
OverflowError
if the value ofpylong is out of range for adouble.Returns
-1.0
on error. UsePyErr_Occurred()
to disambiguate.
- void*PyLong_AsVoidPtr(PyObject*pylong)¶
- 為穩定 ABI 的一部分.
Convert a Python integerpylong to a Cvoid pointer.Ifpylong cannot be converted, an
OverflowError
will be raised. Thisis only assured to produce a usablevoid pointer for values createdwithPyLong_FromVoidPtr()
.Returns
NULL
on error. UsePyErr_Occurred()
to disambiguate.
- Py_ssize_tPyLong_AsNativeBytes(PyObject*pylong,void*buffer,Py_ssize_tn_bytes,intflags)¶
- 為穩定 ABI 的一部分 自 3.14 版本開始.
Copy the Python integer valuepylong to a nativebuffer of sizen_bytes. Theflags can be set to
-1
to behave similarly to a C cast,or to values documented below to control the behavior.Returns
-1
with an exception raised on error. This may happen ifpylong cannot be interpreted as an integer, or ifpylong was negativeand thePy_ASNATIVEBYTES_REJECT_NEGATIVE
flag 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.
備註
Overflow is not considered an error. If the returned valueis larger thann_bytes, most significant bits were discarded.
0
將永不被回傳。Values are always copied as two's-complement.
使用範例:
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
.備註
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-1
cannot be combined with other flags.Currently,
-1
corresponds toPy_ASNATIVEBYTES_NATIVE_ENDIAN|Py_ASNATIVEBYTES_UNSIGNED_BUFFER
.旗標
數值
- 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¶
16
Specifying
Py_ASNATIVEBYTES_NATIVE_ENDIAN
will override any other endianflags. Passing2
is 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_BUFFER
is 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_NEGATIVE
causes 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_BUFFER
was specified.If
Py_ASNATIVEBYTES_ALLOW_INDEX
is 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
.備註
With the defaultflags (
-1
, orUNSIGNED_BUFFER withoutREJECT_NEGATIVE), multiple Python integers can map to a single valuewithout overflow. For example, both255
and-1
fit a single-bytebuffer and set all its bits.This matches typical C cast behavior.在 3.13 版被加入.
- Py_ASNATIVEBYTES_DEFAULTS¶
- intPyLong_GetSign(PyObject*obj,int*sign)¶
Get the sign of the integer objectobj.
On success, set*sign to the integer sign (0, -1 or +1 for zero, negative orpositive integer, respectively) and return 0.
On failure, return -1 with an exception set. This function always succeedsifobj is a
PyLongObject
or its subtype.在 3.14 版被加入.
- intPyLong_IsPositive(PyObject*obj)¶
Check if the integer objectobj is positive (
obj>0
).Ifobj is an instance of
PyLongObject
or its subtype,return1
when it's positive and0
otherwise. Else set anexception and return-1
.在 3.14 版被加入.
- intPyLong_IsNegative(PyObject*obj)¶
Check if the integer objectobj is negative (
obj<0
).Ifobj is an instance of
PyLongObject
or its subtype,return1
when it's negative and0
otherwise. Else set anexception and return-1
.在 3.14 版被加入.
- intPyLong_IsZero(PyObject*obj)¶
Check if the integer objectobj is zero.
Ifobj is an instance of
PyLongObject
or its subtype,return1
when it's zero and0
otherwise. Else set anexception and return-1
.在 3.14 版被加入.
- PyObject*PyLong_GetInfo(void)¶
- 為穩定 ABI 的一部分.
On success, return a read onlynamed tuple, that holdsinformation about Python's internal representation of integers.See
sys.int_info
for description of individual fields.在失敗時,會回傳
NULL
並設定例外。在 3.1 版被加入.
- intPyUnstable_Long_IsCompact(constPyLongObject*op)¶
- 這是不穩定 API,它可能在小版本發布中沒有任何警告地被變更。
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.
在 3.12 版被加入.
- Py_ssize_tPyUnstable_Long_CompactValue(constPyLongObject*op)¶
- 這是不穩定 API,它可能在小版本發布中沒有任何警告地被變更。
Ifop is compact, as determined by
PyUnstable_Long_IsCompact()
,return its value.Otherwise, the return value is undefined.
在 3.12 版被加入.
Export API¶
在 3.14 版被加入.
- structPyLongLayout¶
Layout of an array of "digits" ("limbs" in the GMP terminology), used torepresent absolute value for arbitrary precision integers.
Use
PyLong_GetNativeLayout()
to get the native layout of Pythonint
objects, used internally for integers with "big enough"absolute value.See also
sys.int_info
which exposes similar information in Python.- uint8_tbits_per_digit¶
Bits per digit. For example, a 15 bit digit means that bits 0-14 containmeaningful information.
- uint8_tdigit_size¶
Digit size in bytes. For example, a 15 bit digit will require at least 2bytes.
- int8_tdigits_order¶
Digits order:
1
for most significant digit first-1
for least significant digit first
- int8_tdigit_endianness¶
Digit endianness:
1
for most significant byte first (big endian)-1
for least significant byte first (little endian)
- uint8_tbits_per_digit¶
- constPyLongLayout*PyLong_GetNativeLayout(void)¶
Get the native layout of Python
int
objects.See the
PyLongLayout
structure.The function must not be called before Python initialization nor afterPython finalization. The returned layout is valid until Python isfinalized. The layout is the same for all Python sub-interpretersin a process, and so it can be cached.
- structPyLongExport¶
Export of a Python
int
object.There are two cases:
- Py_ssize_tndigits¶
Number of digits in
digits
array.Only valid ifdigits
is notNULL
.
- constvoid*digits¶
Read-only array of unsigned digits. Can be
NULL
.
- intPyLong_Export(PyObject*obj,PyLongExport*export_long)¶
Export a Python
int
object.export_long must point to a
PyLongExport
structure allocatedby the caller. It must not beNULL
.On success, fill in*export_long and return
0
.On error, set an exception and return-1
.PyLong_FreeExport()
must be called when the export is no longerneeded.CPython 實作細節: This function always succeeds ifobj is a Python
int
objector a subclass.
- voidPyLong_FreeExport(PyLongExport*export_long)¶
Release the exportexport_long created by
PyLong_Export()
.CPython 實作細節: Calling
PyLong_FreeExport()
is optional ifexport_long->digitsisNULL
.
PyLongWriter API¶
ThePyLongWriter
API can be used to import an integer.
在 3.14 版被加入.
- structPyLongWriter¶
A Python
int
writer instance.The instance must be destroyed by
PyLongWriter_Finish()
orPyLongWriter_Discard()
.
- PyLongWriter*PyLongWriter_Create(intnegative,Py_ssize_tndigits,void**digits)¶
Create a
PyLongWriter
.On success, allocate*digits and return a writer.On error, set an exception and return
NULL
.negative is
1
if the number is negative, or0
otherwise.ndigits is the number of digits in thedigits array. It must begreater than 0.
digits must not be NULL.
After a successful call to this function, the caller should fill in thearray of digitsdigits and then call
PyLongWriter_Finish()
to geta Pythonint
.The layout ofdigits is described byPyLong_GetNativeLayout()
.Digits must be in the range [
0
;(1<<bits_per_digit)-1
](where thebits_per_digit
is the number of bitsper digit).Any unused most significant digits must be set to0
.Alternately, call
PyLongWriter_Discard()
to destroy the writerinstance without creating anint
object.
- PyObject*PyLongWriter_Finish(PyLongWriter*writer)¶
- 回傳值:新的參照。
Finish a
PyLongWriter
created byPyLongWriter_Create()
.On success, return a Python
int
object.On error, set an exception and returnNULL
.The function takes care of normalizing the digits and converts the objectto a compact integer if needed.
The writer instance and thedigits array are invalid after the call.
- voidPyLongWriter_Discard(PyLongWriter*writer)¶
Discard a
PyLongWriter
created byPyLongWriter_Create()
.Ifwriter is
NULL
, no operation is performed.The writer instance and thedigits array are invalid after the call.