通用物件結構

大量的结构体被用于定义Python的对象类型。这一节描述了这些的结构体和它们的使用方法。

基本的对象类型和宏

所有的 Python 对象都在对象的内存表示的开始部分共享少量的字段。 这些字段用 PyObjectPyVarObject 类型来表示,这些类型又由一些宏定义,这些宏也直接或间接地用于所有其他 Python 对象的定义。

type PyObject
Part of the Limited API. (Only some members are part of the stable ABI.)

所有对象类型都是此类型的扩展。 这是一个包含了 Python 将对象的指针当作对象来处理所需的信息的类型。 在一个普通的“发行”编译版中,它只包含对象的引用计数和指向对应类型对象的指针。 没有什么对象被实际声明为 PyObject,但每个指向 Python 对象的指针都可以被转换为 PyObject*。 对成员的访问必须通过使用 Py_REFCNTPy_TYPE 宏来完成。

type PyVarObject
Part of the Limited API. (Only some members are part of the stable ABI.)

This is an extension of PyObject that adds the ob_size field. This is only used for objects that have some notion of length. This type does not often appear in the Python/C API. Access to the members must be done by using the macros Py_REFCNT, Py_TYPE, and Py_SIZE.

PyObject_HEAD

这是一个在声明代表无可变长度对象的新类型时所使用的宏。 PyObject_HEAD 宏被扩展为:

PyObject ob_base;

参见上面 PyObject 的文档。

PyObject_VAR_HEAD

这是一个在声明代表每个实例具有可变长度的对象时所使用的宏。 PyObject_VAR_HEAD 宏被扩展为:

PyVarObject ob_base;

参见上面 PyVarObject 的文档。

int Py_Is(const PyObject *x, const PyObject *y)
Part of the Stable ABI since version 3.10.

测试 x 是否为 y 对象,与 Python 中的 x is y 相同。

3.10 版新加入.

int Py_IsNone(const PyObject *x)
Part of the Stable ABI since version 3.10.

测试一个对象是否为 None 单例,与 Python 中的 x is None 相同。

3.10 版新加入.

int Py_IsTrue(const PyObject *x)
Part of the Stable ABI since version 3.10.

测试一个对象是否为 True 单例,与 Python 中的 x is True 相同。

3.10 版新加入.

int Py_IsFalse(const PyObject *x)
Part of the Stable ABI since version 3.10.

测试一个对象是否为 False 单例,与 Python 中的 x is False 相同。

3.10 版新加入.

PyTypeObject *Py_TYPE(const PyObject *o)

获取 Python 对象 o 的类型。

返回一个 borrowed reference

使用 Py_SET_TYPE() 函数来设置一个对象类型。

int Py_IS_TYPE(PyObject *o, PyTypeObject *type)

如果对象 o 的类型为 type 则返回非零值。 否则返回零。 等价于: Py_TYPE(o) == type

3.9 版新加入.

void Py_SET_TYPE(PyObject *o, PyTypeObject *type)

将对象 o 的类型设为 type

3.9 版新加入.

Py_ssize_t Py_REFCNT(const PyObject *o)

获取 Python 对象 o 的引用计数。

3.10 版更變: Py_REFCNT() is changed to the inline static function. Use Py_SET_REFCNT() to set an object reference count.

void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)

将对象 o 的引用计数器设为 refcnt

3.9 版新加入.

Py_ssize_t Py_SIZE(const PyVarObject *o)

获取 Python 对象 o 的大小。

使用 Py_SET_SIZE() 函数来设置一个对象大小。

void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)

将对象 o 的大小设为 size

3.9 版新加入.

PyObject_HEAD_INIT(type)

这是一个为新的 PyObject 类型扩展初始化值的宏。 该宏扩展为:

_PyObject_EXTRA_INIT
1, type,
PyVarObject_HEAD_INIT(type, size)

This is a macro which expands to initialization values for a new PyVarObject type, including the ob_size field. This macro expands to:

_PyObject_EXTRA_INIT
1, type, size,

实现函数和方法

type PyCFunction
Part of the Stable ABI.

用于在 C 中实现大多数 Python 可调用对象的函数类型。 该类型的函数接受两个 PyObject* 形参并返回一个这样的值。 如果返回值为 NULL,则将设置一个异常。 如果不为 NULL,则返回值将被解读为 Python 中暴露的函数的返回值。 此函数必须返回一个新的引用。

函数的签名为:

PyObject *PyCFunction(PyObject *self,
                      PyObject *args);
type PyCFunctionWithKeywords
Part of the Stable ABI.

Type of the functions used to implement Python callables in C with signature METH_VARARGS | METH_KEYWORDS. The function signature is:

PyObject *PyCFunctionWithKeywords(PyObject *self,
                                  PyObject *args,
                                  PyObject *kwargs);
type _PyCFunctionFast

Type of the functions used to implement Python callables in C with signature METH_FASTCALL. The function signature is:

PyObject *_PyCFunctionFast(PyObject *self,
                           PyObject *const *args,
                           Py_ssize_t nargs);
type _PyCFunctionFastWithKeywords

Type of the functions used to implement Python callables in C with signature METH_FASTCALL | METH_KEYWORDS. The function signature is:

PyObject *_PyCFunctionFastWithKeywords(PyObject *self,
                                       PyObject *const *args,
                                       Py_ssize_t nargs,
                                       PyObject *kwnames);
type PyCMethod

Type of the functions used to implement Python callables in C with signature METH_METHOD | METH_FASTCALL | METH_KEYWORDS. The function signature is:

PyObject *PyCMethod(PyObject *self,
                    PyTypeObject *defining_class,
                    PyObject *const *args,
                    Py_ssize_t nargs,
                    PyObject *kwnames)

3.9 版新加入.

type PyMethodDef
Part of the Stable ABI (including all members).

用于描述一个扩展类型的方法的结构体。 该结构体有四个字段:

const char *ml_name

name of the method

PyCFunction ml_meth

pointer to the C implementation

int ml_flags

flags bits indicating how the call should be constructed

const char *ml_doc

points to the contents of the docstring

The ml_meth is a C function pointer. The functions may be of different types, but they always return PyObject*. If the function is not of the PyCFunction, the compiler will require a cast in the method table. Even though PyCFunction defines the first parameter as PyObject*, it is common that the method implementation uses the specific C type of the self object.

The ml_flags field is a bitfield which can include the following flags. The individual flags indicate either a calling convention or a binding convention.

调用惯例有如下这些:

METH_VARARGS

这是典型的调用惯例,其中方法的类型为 PyCFunction。 该函数接受两个 PyObject* 值。 第一个是用于方法的 self 对象;对于模块函数,它将为模块对象。 第二个形参 (常被命名为 args) 是一个代表所有参数的元组对象。 该形参通常是使用 PyArg_ParseTuple()PyArg_UnpackTuple() 来处理的。

METH_VARARGS | METH_KEYWORDS

带有这些旗标的方法必须为 PyCFunctionWithKeywords 类型。 该函数接受三个形参: self, args, kwargs 其中 kwargs 是一个包含所有关键字参数的字典或者如果没有关键字参数则可以为 NULL。 这些形参通常是使用 PyArg_ParseTupleAndKeywords() 来处理的。

METH_FASTCALL

快速调用惯例仅支持位置参数。 这些方法的类型为 _PyCFunctionFast。 第一个形参为 self,第二个形参是由表示参数的 PyObject* 值组成的数组而第三个形参是参数的数量(数组的长度)。

3.7 版新加入.

3.10 版更變: METH_FASTCALL is now part of the stable ABI.

METH_FASTCALL | METH_KEYWORDS

Extension of METH_FASTCALL supporting also keyword arguments, with methods of type _PyCFunctionFastWithKeywords. Keyword arguments are passed the same way as in the vectorcall protocol: there is an additional fourth PyObject* parameter which is a tuple representing the names of the keyword arguments (which are guaranteed to be strings) or possibly NULL if there are no keywords. The values of the keyword arguments are stored in the args array, after the positional arguments.

3.7 版新加入.

METH_METHOD | METH_FASTCALL | METH_KEYWORDS

Extension of METH_FASTCALL | METH_KEYWORDS supporting the defining class, that is, the class that contains the method in question. The defining class might be a superclass of Py_TYPE(self).

该方法必须为 PyCMethod 类型,与在 self 之后添加了 defining_class 参数的 METH_FASTCALL | METH_KEYWORDS 一样。

3.9 版新加入.

METH_NOARGS

Methods without parameters don't need to check whether arguments are given if they are listed with the METH_NOARGS flag. They need to be of type PyCFunction. The first parameter is typically named self and will hold a reference to the module or object instance. In all cases the second parameter will be NULL.

METH_O

Methods with a single object argument can be listed with the METH_O flag, instead of invoking PyArg_ParseTuple() with a "O" argument. They have the type PyCFunction, with the self parameter, and a PyObject* parameter representing the single argument.

这两个常量不是被用来指明调用惯例而是在配合类方法使用时指明绑定。 它们不会被用于在模块上定义的函数。 对于任何给定方法这些旗标最多只会设置其中一个。

METH_CLASS

该方法将接受类型对象而不是类型的实例作为第一个形参。 它会被用于创建 类方法,类似于使用 classmethod() 内置函数所创建的结果。

METH_STATIC

该方法将接受 NULL 而不是类型的实例作为第一个形参。 它会被用于创建 静态方法,类似于使用 staticmethod() 内置函数所创建的结果。

另一个常量控制方法是否将被载入来替代具有相同方法名的另一个定义。

METH_COEXIST

The method will be loaded in place of existing definitions. Without METH_COEXIST, the default is to skip repeated definitions. Since slot wrappers are loaded before the method table, the existence of a sq_contains slot, for example, would generate a wrapped method named __contains__() and preclude the loading of a corresponding PyCFunction with the same name. With the flag defined, the PyCFunction will be loaded in place of the wrapper object and will co-exist with the slot. This is helpful because calls to PyCFunctions are optimized more than wrapper object calls.

访问扩展类型的属性

type PyMemberDef
Part of the Stable ABI (including all members).

Structure which describes an attribute of a type which corresponds to a C struct member. Its fields are:

C Type

含意

name

const char *

name of the member

type

int

the type of the member in the C struct

offset

Py_ssize_t

the offset in bytes that the member is located on the type's object struct

flags

int

flag bits indicating if the field should be read-only or writable

doc

const char *

points to the contents of the docstring

type can be one of many T_ macros corresponding to various C types. When the member is accessed in Python, it will be converted to the equivalent Python type.

宏名称

C 类型

T_SHORT

short

T_INT

int

T_LONG

long

T_FLOAT

float

T_DOUBLE

double

T_STRING

const char *

T_OBJECT

PyObject *

T_OBJECT_EX

PyObject *

T_CHAR

char

T_BYTE

char

T_UBYTE

unsigned char

T_UINT

unsigned int

T_USHORT

unsigned short

T_ULONG

unsigned long

T_BOOL

char

T_LONGLONG

long long

T_ULONGLONG

unsigned long long

T_PYSSIZET

Py_ssize_t

T_OBJECT and T_OBJECT_EX differ in that T_OBJECT returns None if the member is NULL and T_OBJECT_EX raises an AttributeError. Try to use T_OBJECT_EX over T_OBJECT because T_OBJECT_EX handles use of the del statement on that attribute more correctly than T_OBJECT.

flags can be 0 for write and read access or READONLY for read-only access. Using T_STRING for type implies READONLY. T_STRING data is interpreted as UTF-8. Only T_OBJECT and T_OBJECT_EX members can be deleted. (They are set to NULL).

Heap allocated types (created using PyType_FromSpec() or similar), PyMemberDef may contain definitions for the special members __dictoffset__, __weaklistoffset__ and __vectorcalloffset__, corresponding to tp_dictoffset, tp_weaklistoffset and tp_vectorcall_offset in type objects. These must be defined with T_PYSSIZET and READONLY, for example:

static PyMemberDef spam_type_members[] = {
    {"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY},
    {NULL}  /* Sentinel */
};
PyObject *PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)

获取属于地址Get an attribute belonging to the object at address obj_addr 上的对象的某个属性。 该属性是以 PyMemberDef m 来描述的。 出错时返回 NULL

int PyMember_SetOne(char *obj_addr, struct PyMemberDef *m, PyObject *o)

将属于位于地址 obj_addr 的对象的属性设置到对象 o。 要设置的属性由 PyMemberDef m 描述。 成功时返回 0 而失败时返回负值。

type PyGetSetDef
Part of the Stable ABI (including all members).

用于定义针对某个类型的特征属性式的访问的结构体。 另请参阅 PyTypeObject.tp_getset 槽位的描述。

C Type

含意

name

const char *

属性名称

get

getter

C function to get the attribute

set

setter

optional C function to set or delete the attribute, if omitted the attribute is readonly

doc

const char *

可选的文档字符串

closure

void *

optional function pointer, providing additional data for getter and setter

get 函数接受一个 PyObject* 形参 (实例) 和一个函数指针 (关联的 closure):

typedef PyObject *(*getter)(PyObject *, void *);

它应当在成功时返回一个新的引用或在失败时返回 NULL 并设置异常。

set 函数接受两个 PyObject* 形参 (实例和要设置的值) 和一个函数指针 (关联的 closure):

typedef int (*setter)(PyObject *, PyObject *, void *);

对于属性要被删除的情况第二个形参应为 NULL。 成功时应返回 0 或在失败时返回 -1 并设置异常。