객체 프로토콜¶
-
PyObject *Py_GetConstant(unsigned int constant_id)¶
- Part of the Stable ABI since version 3.13.
Get a strong reference to a constant.
Set an exception and return
NULL
if constant_id is invalid.constant_id must be one of these constant identifiers:
Constant Identifier
Value
Returned object
-
Py_CONSTANT_NONE¶
0
-
Py_CONSTANT_FALSE¶
1
-
Py_CONSTANT_TRUE¶
2
-
Py_CONSTANT_ELLIPSIS¶
3
-
Py_CONSTANT_NOT_IMPLEMENTED¶
4
-
Py_CONSTANT_ZERO¶
5
0
-
Py_CONSTANT_ONE¶
6
1
-
Py_CONSTANT_EMPTY_STR¶
7
''
-
Py_CONSTANT_EMPTY_BYTES¶
8
b''
-
Py_CONSTANT_EMPTY_TUPLE¶
9
()
Numeric values are only given for projects which cannot use the constant identifiers.
Added in version 3.13.
CPython 구현 상세: In CPython, all of these constants are immortal.
-
Py_CONSTANT_NONE¶
-
PyObject *Py_GetConstantBorrowed(unsigned int constant_id)¶
- Part of the Stable ABI since version 3.13.
Similar to
Py_GetConstant()
, but return a borrowed reference.This function is primarily intended for backwards compatibility: using
Py_GetConstant()
is recommended for new code.The reference is borrowed from the interpreter, and is valid until the interpreter finalization.
Added in version 3.13.
-
Py_RETURN_NOTIMPLEMENTED¶
Properly handle returning
Py_NotImplemented
from within a C function (that is, create a new strong reference toNotImplemented
and return it).
-
Py_PRINT_RAW¶
Flag to be used with multiple functions that print the object (like
PyObject_Print()
andPyFile_WriteObject()
). If passed, these function would use thestr()
of the object instead of therepr()
.
-
int PyObject_Print(PyObject *o, FILE *fp, int flags)¶
Print an object o, on file fp. Returns
-1
on error. The flags argument is used to enable certain printing options. The only option currently supported isPy_PRINT_RAW
; if given, thestr()
of the object is written instead of therepr()
.
-
int PyObject_HasAttrWithError(PyObject *o, PyObject *attr_name)¶
- Part of the Stable ABI since version 3.13.
Returns
1
if o has the attribute attr_name, and0
otherwise. This is equivalent to the Python expressionhasattr(o, attr_name)
. On failure, return-1
.Added in version 3.13.
-
int PyObject_HasAttrStringWithError(PyObject *o, const char *attr_name)¶
- Part of the Stable ABI since version 3.13.
This is the same as
PyObject_HasAttrWithError()
, but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.Added in version 3.13.
-
int PyObject_HasAttr(PyObject *o, PyObject *attr_name)¶
- Part of the Stable ABI.
Returns
1
if o has the attribute attr_name, and0
otherwise. This function always succeeds.참고
Exceptions that occur when this calls
__getattr__()
and__getattribute__()
methods are silently ignored. For proper error handling, usePyObject_HasAttrWithError()
,PyObject_GetOptionalAttr()
orPyObject_GetAttr()
instead.
-
int PyObject_HasAttrString(PyObject *o, const char *attr_name)¶
- Part of the Stable ABI.
This is the same as
PyObject_HasAttr()
, but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.참고
Exceptions that occur when this calls
__getattr__()
and__getattribute__()
methods or while creating the temporarystr
object are silently ignored. For proper error handling, usePyObject_HasAttrStringWithError()
,PyObject_GetOptionalAttrString()
orPyObject_GetAttrString()
instead.
-
PyObject *PyObject_GetAttr(PyObject *o, PyObject *attr_name)¶
- Return value: New reference. Part of the Stable ABI.
객체 o에서 attr_name이라는 이름의 어트리뷰트를 가져옵니다. 성공하면 어트리뷰트 값을, 실패하면
NULL
을 반환합니다. 이것은 파이썬 표현식o.attr_name
과 동등합니다.If the missing attribute should not be treated as a failure, you can use
PyObject_GetOptionalAttr()
instead.
-
PyObject *PyObject_GetAttrString(PyObject *o, const char *attr_name)¶
- Return value: New reference. Part of the Stable ABI.
This is the same as
PyObject_GetAttr()
, but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.If the missing attribute should not be treated as a failure, you can use
PyObject_GetOptionalAttrString()
instead.
-
int PyObject_GetOptionalAttr(PyObject *obj, PyObject *attr_name, PyObject **result);¶
- Part of the Stable ABI since version 3.13.
Variant of
PyObject_GetAttr()
which doesn’t raiseAttributeError
if the attribute is not found.If the attribute is found, return
1
and set *result to a new strong reference to the attribute. If the attribute is not found, return0
and set *result toNULL
; theAttributeError
is silenced. If an error other thanAttributeError
is raised, return-1
and set *result toNULL
.Added in version 3.13.
-
int PyObject_GetOptionalAttrString(PyObject *obj, const char *attr_name, PyObject **result);¶
- Part of the Stable ABI since version 3.13.
This is the same as
PyObject_GetOptionalAttr()
, but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.Added in version 3.13.
-
PyObject *PyObject_GenericGetAttr(PyObject *o, PyObject *name)¶
- Return value: New reference. Part of the Stable ABI.
형 객체의
tp_getattro
슬롯에 배치되는 일반 어트리뷰트 게터(getter) 함수. 객체의 (있다면)__dict__
에 있는 어트리뷰트뿐만 아니라 객체의 MRO에 있는 클래스의 딕셔너리에 있는 디스크립터를 찾습니다. 디스크립터 구현하기에 요약된 것처럼, 데이터 디스크립터는 인스턴스 어트리뷰트보다 우선하지만, 비 데이터 디스크립터는 그렇지 않습니다. 그렇지 않으면,AttributeError
가 발생합니다.
-
int PyObject_SetAttr(PyObject *o, PyObject *attr_name, PyObject *v)¶
- Part of the Stable ABI.
객체 o에 대해, attr_name이라는 이름의 어트리뷰트 값을 v 값으로 설정합니다. 실패 시 예외를 발생시키고
-1
을 반환합니다. 성공하면0
을 반환합니다. 이것은 파이썬 문장o.attr_name = v
와 동등합니다.If v is
NULL
, the attribute is deleted. This behaviour is deprecated in favour of usingPyObject_DelAttr()
, but there are currently no plans to remove it.
-
int PyObject_SetAttrString(PyObject *o, const char *attr_name, PyObject *v)¶
- Part of the Stable ABI.
This is the same as
PyObject_SetAttr()
, but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.If v is
NULL
, the attribute is deleted, but this feature is deprecated in favour of usingPyObject_DelAttrString()
.The number of different attribute names passed to this function should be kept small, usually by using a statically allocated string as attr_name. For attribute names that aren’t known at compile time, prefer calling
PyUnicode_FromString()
andPyObject_SetAttr()
directly. For more details, seePyUnicode_InternFromString()
, which may be used internally to create a key object.
-
int PyObject_GenericSetAttr(PyObject *o, PyObject *name, PyObject *value)¶
- Part of the Stable ABI.
형 객체의
tp_setattro
슬롯에 배치되는 일반 어트리뷰트 세터(setter)와 딜리터(deleter) 함수. 객체의 MRO에 있는 클래스의 딕셔너리에서 데이터 디스크립터를 찾고, 발견되면 인스턴스 딕셔너리에 있는 어트리뷰트를 설정하거나 삭제하는 것보다 우선합니다. 그렇지 않으면, 객체의 (있다면)__dict__
에서 어트리뷰트가 설정되거나 삭제됩니다. 성공하면0
이 반환되고, 그렇지 않으면AttributeError
가 발생하고-1
이 반환됩니다.
-
int PyObject_DelAttr(PyObject *o, PyObject *attr_name)¶
- Part of the Stable ABI since version 3.13.
객체 o에 대해, attr_name이라는 이름의 어트리뷰트를 삭제합니다. 실패 시
-1
을 반환합니다. 이것은 파이썬 문장del o.attr_name
과 동등합니다.
-
int PyObject_DelAttrString(PyObject *o, const char *attr_name)¶
- Part of the Stable ABI since version 3.13.
This is the same as
PyObject_DelAttr()
, but attr_name is specified as a const char* UTF-8 encoded bytes string, rather than a PyObject*.The number of different attribute names passed to this function should be kept small, usually by using a statically allocated string as attr_name. For attribute names that aren’t known at compile time, prefer calling
PyUnicode_FromString()
andPyObject_DelAttr()
directly. For more details, seePyUnicode_InternFromString()
, which may be used internally to create a key object for lookup.
-
PyObject *PyObject_GenericGetDict(PyObject *o, void *context)¶
- Return value: New reference. Part of the Stable ABI since version 3.10.
__dict__
디스크립터의 게터(getter)를 위한 일반적인 구현. 필요하면 딕셔너리를 만듭니다.This function may also be called to get the
__dict__
of the object o. PassNULL
for context when calling it. Since this function may need to allocate memory for the dictionary, it may be more efficient to callPyObject_GetAttr()
when accessing an attribute on the object.On failure, returns
NULL
with an exception set.Added in version 3.3.
-
int PyObject_GenericSetDict(PyObject *o, PyObject *value, void *context)¶
- Part of the Stable ABI since version 3.7.
__dict__
디스크립터의 세터(setter)를 위한 일반적인 구현. 이 구현은 딕셔너리 삭제를 허락하지 않습니다.Added in version 3.3.
-
PyObject **_PyObject_GetDictPtr(PyObject *obj)¶
Return a pointer to
__dict__
of the object obj. If there is no__dict__
, returnNULL
without setting an exception.This function may need to allocate memory for the dictionary, so it may be more efficient to call
PyObject_GetAttr()
when accessing an attribute on the object.
-
PyObject *PyObject_RichCompare(PyObject *o1, PyObject *o2, int opid)¶
- Return value: New reference. Part of the Stable ABI.
Compare the values of o1 and o2 using the operation specified by opid, which must be one of
Py_LT
,Py_LE
,Py_EQ
,Py_NE
,Py_GT
, orPy_GE
, corresponding to<
,<=
,==
,!=
,>
, or>=
respectively. This is the equivalent of the Python expressiono1 op o2
, whereop
is the operator corresponding to opid. Returns the value of the comparison on success, orNULL
on failure.
-
int PyObject_RichCompareBool(PyObject *o1, PyObject *o2, int opid)¶
- Part of the Stable ABI.
Compare the values of o1 and o2 using the operation specified by opid, like
PyObject_RichCompare()
, but returns-1
on error,0
if the result is false,1
otherwise.
참고
If o1 and o2 are the same object, PyObject_RichCompareBool()
will always return 1
for Py_EQ
and 0
for Py_NE
.
-
PyObject *PyObject_Format(PyObject *obj, PyObject *format_spec)¶
- Part of the Stable ABI.
Format obj using format_spec. This is equivalent to the Python expression
format(obj, format_spec)
.format_spec may be
NULL
. In this case the call is equivalent toformat(obj)
. Returns the formatted string on success,NULL
on failure.
-
PyObject *PyObject_Repr(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
객체 o의 문자열 표현을 계산합니다. 성공하면 문자열 표현을, 실패하면
NULL
을 반환합니다. 이것은 파이썬 표현식repr(o)
와 동등합니다.repr()
내장 함수에 의해 호출됩니다.버전 3.4에서 변경: 이 함수에는 이제 디버그 어서션이 포함되어 있어 활성 예외를 조용히 버리지 않도록 합니다.
-
PyObject *PyObject_ASCII(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
PyObject_Repr()
처럼, 객체 o의 문자열 표현을 계산하지만,\x
,\u
또는\U
이스케이프를 사용하여PyObject_Repr()
이 반환한 문자열에서 비 ASCII 문자를 이스케이프 합니다. 이것은 파이썬 2에서PyObject_Repr()
에 의해 반환된 것과 유사한 문자열을 생성합니다.ascii()
내장 함수에 의해 호출됩니다.
-
PyObject *PyObject_Str(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
객체 o의 문자열 표현을 계산합니다. 성공 시 문자열 표현을, 실패 시
NULL
을 반환합니다. 이것은 파이썬 표현식str(o)
와 동등합니다.str()
내장 함수에 의해, 따라서print()
함수에 의해서도 호출됩니다.버전 3.4에서 변경: 이 함수에는 이제 디버그 어서션이 포함되어 있어 활성 예외를 조용히 버리지 않도록 합니다.
-
PyObject *PyObject_Bytes(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
객체 o의 바이트열 표현을 계산합니다. 실패하면
NULL
을, 성공하면 바이트열 객체를 반환됩니다. 이는 o가 정수가 아닐 때 파이썬 표현식bytes(o)
와 동등합니다.bytes(o)
와 달리, o가 정수이면 0으로 초기화된 바이트열 객체 대신 TypeError가 발생합니다.
-
int PyObject_IsSubclass(PyObject *derived, PyObject *cls)¶
- Part of the Stable ABI.
클래스 derived가 클래스 cls와 동일하거나 cls에서 파생되었으면
1
을 반환하고, 그렇지 않으면0
을 반환합니다. 에러가 발생하면-1
을 반환합니다.cls가 튜플이면, cls의 모든 항목에 대해 검사가 수행됩니다. 적어도 하나의 검사에서
1
을 반환하면 결과는1
이 되고, 그렇지 않으면0
이 됩니다.If cls has a
__subclasscheck__()
method, it will be called to determine the subclass status as described in PEP 3119. Otherwise, derived is a subclass of cls if it is a direct or indirect subclass, i.e. contained incls.__mro__
.Normally only class objects, i.e. instances of
type
or a derived class, are considered classes. However, objects can override this by having a__bases__
attribute (which must be a tuple of base classes).
-
int PyObject_IsInstance(PyObject *inst, PyObject *cls)¶
- Part of the Stable ABI.
inst가 cls 클래스나 cls의 서브 클래스의 인스턴스이면
1
을 반환하고, 그렇지 않으면0
을 반환합니다. 에러가 발생하면-1
을 반환하고 예외를 설정합니다.cls가 튜플이면, cls의 모든 항목에 대해 검사가 수행됩니다. 적어도 하나의 검사에서
1
을 반환하면 결과는1
이 되고, 그렇지 않으면0
이 됩니다.If cls has a
__instancecheck__()
method, it will be called to determine the subclass status as described in PEP 3119. Otherwise, inst is an instance of cls if its class is a subclass of cls.An instance inst can override what is considered its class by having a
__class__
attribute.An object cls can override if it is considered a class, and what its base classes are, by having a
__bases__
attribute (which must be a tuple of base classes).
-
Py_hash_t PyObject_Hash(PyObject *o)¶
- Part of the Stable ABI.
객체 o의 해시값을 계산하고 반환합니다. 실패하면
-1
을 반환합니다. 이것은 파이썬 표현식hash(o)
와 동등합니다.버전 3.2에서 변경: The return type is now Py_hash_t. This is a signed integer the same size as
Py_ssize_t
.
-
Py_hash_t PyObject_HashNotImplemented(PyObject *o)¶
- Part of the Stable ABI.
Set a
TypeError
indicating thattype(o)
is not hashable and return-1
. This function receives special treatment when stored in atp_hash
slot, allowing a type to explicitly indicate to the interpreter that it is not hashable.
-
int PyObject_IsTrue(PyObject *o)¶
- Part of the Stable ABI.
객체 o를 참으로 간주하면
1
을, 그렇지 않으면0
을 반환합니다. 이것은 파이썬 표현식not not o
와 동등합니다. 실패하면-1
을 반환합니다.
-
int PyObject_Not(PyObject *o)¶
- Part of the Stable ABI.
객체 o를 참으로 간주하면
0
을, 그렇지 않으면1
을 반환합니다. 이것은 파이썬 표현식not o
와 동등합니다. 실패하면-1
을 반환합니다.
-
PyObject *PyObject_Type(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
When o is non-
NULL
, returns a type object corresponding to the object type of object o. On failure, raisesSystemError
and returnsNULL
. This is equivalent to the Python expressiontype(o)
. This function creates a new strong reference to the return value. There’s really no reason to use this function instead of thePy_TYPE()
function, which returns a pointer of type PyTypeObject*, except when a new strong reference is needed.
-
int PyObject_TypeCheck(PyObject *o, PyTypeObject *type)¶
Return non-zero if the object o is of type type or a subtype of type, and
0
otherwise. Both parameters must be non-NULL
.
-
Py_ssize_t PyObject_Size(PyObject *o)¶
-
Py_ssize_t PyObject_Length(PyObject *o)¶
- Part of the Stable ABI.
객체 o의 길이를 반환합니다. 객체 o가 시퀀스와 매핑 프로토콜을 제공하면, 시퀀스 길이가 반환됩니다. 에러가 발생하면
-1
이 반환됩니다. 이것은 파이썬 표현식len(o)
와 동등합니다.
-
Py_ssize_t PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)¶
Return an estimated length for the object o. First try to return its actual length, then an estimate using
__length_hint__()
, and finally return the default value. On error return-1
. This is the equivalent to the Python expressionoperator.length_hint(o, defaultvalue)
.Added in version 3.4.
-
PyObject *PyObject_GetItem(PyObject *o, PyObject *key)¶
- Return value: New reference. Part of the Stable ABI.
객체 key에 해당하는 o의 요소를 반환하거나 실패 시
NULL
을 반환합니다. 이것은 파이썬 표현식o[key]
와 동등합니다.
-
int PyObject_SetItem(PyObject *o, PyObject *key, PyObject *v)¶
- Part of the Stable ABI.
객체 key를 값 v에 매핑합니다. 실패 시 예외를 발생시키고
-1
을 반환합니다; 성공하면0
을 반환합니다. 이것은 파이썬 문장o[key] = v
와 동등합니다. 이 함수는 v에 대한 참조를 훔치지 않습니다.
-
int PyObject_DelItem(PyObject *o, PyObject *key)¶
- Part of the Stable ABI.
객체 o에서 객체 key에 대한 매핑을 제거합니다. 실패하면
-1
을 반환합니다. 이것은 파이썬 문장del o[key]
와 동등합니다.
-
PyObject *PyObject_Dir(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
이것은 파이썬 표현식
dir(o)
와 동등하며, 객체 인자에 적합한 문자열의 (비어있을 수 있는) 리스트를 반환하거나, 에러가 있으면NULL
을 반환합니다. 인자가NULL
이면, 파이썬dir()
과 비슷하며, 현재 지역(locals)의 이름들을 반환합니다; 이 경우, 실행 프레임이 활성화되어 있지 않으면NULL
이 반환되지만PyErr_Occurred()
는 거짓을 반환합니다.
-
PyObject *PyObject_GetIter(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI.
이것은 파이썬 표현식
iter(o)
와 동등합니다. 객체 인자에 대한 새로운 이터레이터를 반환하거나, 객체가 이미 이터레이터이면 객체 자체를 반환합니다. 객체를 이터레이트 할 수 없으면TypeError
를 발생시키고NULL
을 반환합니다.
-
PyObject *PyObject_SelfIter(PyObject *obj)¶
- Return value: New reference. Part of the Stable ABI.
This is equivalent to the Python
__iter__(self): return self
method. It is intended for iterator types, to be used in thePyTypeObject.tp_iter
slot.
-
PyObject *PyObject_GetAIter(PyObject *o)¶
- Return value: New reference. Part of the Stable ABI since version 3.10.
This is the equivalent to the Python expression
aiter(o)
. Takes anAsyncIterable
object and returns anAsyncIterator
for it. This is typically a new iterator but if the argument is anAsyncIterator
, this returns itself. RaisesTypeError
and returnsNULL
if the object cannot be iterated.Added in version 3.10.
-
void *PyObject_GetTypeData(PyObject *o, PyTypeObject *cls)¶
- Part of the Stable ABI since version 3.12.
Get a pointer to subclass-specific data reserved for cls.
The object o must be an instance of cls, and cls must have been created using negative
PyType_Spec.basicsize
. Python does not check this.On error, set an exception and return
NULL
.Added in version 3.12.
-
Py_ssize_t PyType_GetTypeDataSize(PyTypeObject *cls)¶
- Part of the Stable ABI since version 3.12.
Return the size of the instance memory space reserved for cls, i.e. the size of the memory
PyObject_GetTypeData()
returns.This may be larger than requested using
-PyType_Spec.basicsize
; it is safe to use this larger size (e.g. withmemset()
).The type cls must have been created using negative
PyType_Spec.basicsize
. Python does not check this.On error, set an exception and return a negative value.
Added in version 3.12.
-
void *PyObject_GetItemData(PyObject *o)¶
Get a pointer to per-item data for a class with
Py_TPFLAGS_ITEMS_AT_END
.On error, set an exception and return
NULL
.TypeError
is raised if o does not havePy_TPFLAGS_ITEMS_AT_END
set.Added in version 3.12.
-
int PyObject_VisitManagedDict(PyObject *obj, visitproc visit, void *arg)¶
Visit the managed dictionary of obj.
This function must only be called in a traverse function of the type which has the
Py_TPFLAGS_MANAGED_DICT
flag set.Added in version 3.13.
-
void PyObject_ClearManagedDict(PyObject *obj)¶
Clear the managed dictionary of obj.
This function must only be called in a traverse function of the type which has the
Py_TPFLAGS_MANAGED_DICT
flag set.Added in version 3.13.
-
int PyUnstable_Object_EnableDeferredRefcount(PyObject *obj)¶
- This is Unstable API. It may change without warning in minor releases.
Enable deferred reference counting on obj, if supported by the runtime. In the free-threaded build, this allows the interpreter to avoid reference count adjustments to obj, which may improve multi-threaded performance. The tradeoff is that obj will only be deallocated by the tracing garbage collector.
This function returns
1
if deferred reference counting is enabled on obj (including when it was enabled before the call), and0
if deferred reference counting is not supported or if the hint was ignored by the runtime. This function is thread-safe, and cannot fail.This function does nothing on builds with the GIL enabled, which do not support deferred reference counting. This also does nothing if obj is not an object tracked by the garbage collector (see
gc.is_tracked()
andPyObject_GC_IsTracked()
).This function is intended to be used soon after obj is created, by the code that creates it.
Added in version 3.14.