公用对象的结构

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

基本的对象类型和宏

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

type PyObject

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

All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object. Nothing is actually declared to be a PyObject, but every pointer to a Python object can be cast to a PyObject*. Access to the members must be done by using the macros Py_REFCNT and Py_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

This is a macro used when declaring new types which represent objects without a varying length. The PyObject_HEAD macro expands to:

  1. PyObject ob_base;

See documentation of PyObject above.

PyObject_VAR_HEAD

This is a macro used when declaring new types which represent objects with a length that varies from instance to instance. The PyObject_VAR_HEAD macro expands to:

  1. PyVarObject ob_base;

参见上面 PyVarObject 的文档。

int Py_Is(PyObject *x, PyObject *y)

Part of the Stable ABI since version 3.10.

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

3.10 新版功能.

int Py_IsNone(PyObject *x)

Part of the Stable ABI since version 3.10.

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

3.10 新版功能.

int Py_IsTrue(PyObject *x)

Part of the Stable ABI since version 3.10.

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

3.10 新版功能.

int Py_IsFalse(PyObject *x)

Part of the Stable ABI since version 3.10.

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

3.10 新版功能.

PyTypeObject *Py_TYPE(PyObject *o)

获取 Python 对象 o 的类型。

返回一个 borrowed reference

Use the Py_SET_TYPE() function to set an object type.

在 3.11 版更改: Py_TYPE() is changed to an inline static function. The parameter type is no longer const PyObject*.

int Py_IS_TYPE(PyObject *o, PyTypeObject *type)

Return non-zero if the object o type is type. Return zero otherwise. Equivalent to: Py_TYPE(o) == type.

3.9 新版功能.

void Py_SET_TYPE(PyObject *o, PyTypeObject *type)

Set the object o type to type.

3.9 新版功能.

Py_ssize_t Py_REFCNT(PyObject *o)

Get the reference count of the Python object o.

Use the Py_SET_REFCNT() function to set an object reference count.

在 3.11 版更改: The parameter type is no longer const PyObject*.

在 3.10 版更改: Py_REFCNT() is changed to the inline static function.

void Py_SET_REFCNT(PyObject *o, Py_ssize_t refcnt)

Set the object o reference counter to refcnt.

3.9 新版功能.

Py_ssize_t Py_SIZE(PyVarObject *o)

Get the size of the Python object o.

Use the Py_SET_SIZE() function to set an object size.

在 3.11 版更改: Py_SIZE() is changed to an inline static function. The parameter type is no longer const PyVarObject*.

void Py_SET_SIZE(PyVarObject *o, Py_ssize_t size)

Set the object o size to size.

3.9 新版功能.

PyObject_HEAD_INIT(type)

This is a macro which expands to initialization values for a new PyObject type. This macro expands to:

  1. _PyObject_EXTRA_INIT
  2. 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:

  1. _PyObject_EXTRA_INIT
  2. 1, type, size,

Implementing functions and methods

type PyCFunction

Part of the Stable ABI.

Type of the functions used to implement most Python callables in C. Functions of this type take two PyObject* parameters and return one such value. If the return value is NULL, an exception shall have been set. If not NULL, the return value is interpreted as the return value of the function as exposed in Python. The function must return a new reference.

The function signature is:

  1. PyObject *PyCFunction(PyObject *self,
  2. 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:

  1. PyObject *PyCFunctionWithKeywords(PyObject *self,
  2. PyObject *args,
  3. PyObject *kwargs);

type _PyCFunctionFast

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

  1. PyObject *_PyCFunctionFast(PyObject *self,
  2. PyObject *const *args,
  3. 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:

  1. PyObject *_PyCFunctionFastWithKeywords(PyObject *self,
  2. PyObject *const *args,
  3. Py_ssize_t nargs,
  4. 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:

  1. PyObject *PyCMethod(PyObject *self,
  2. PyTypeObject *defining_class,
  3. PyObject *const *args,
  4. Py_ssize_t nargs,
  5. PyObject *kwnames)

3.9 新版功能.

type PyMethodDef

Part of the Stable ABI (including all members).

Structure used to describe a method of an extension type. This structure has four fields:

C 类型

含意

ml_name

const char

name of the method

ml_meth

PyCFunction

pointer to the C implementation

ml_flags

int

flag bits indicating how the call should be constructed

ml_doc

const char

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.

There are these calling conventions:

METH_VARARGS

This is the typical calling convention, where the methods have the type PyCFunction. The function expects two PyObject* values. The first one is the self object for methods; for module functions, it is the module object. The second parameter (often called args) is a tuple object representing all arguments. This parameter is typically processed using PyArg_ParseTuple() or PyArg_UnpackTuple().

METH_VARARGS | METH_KEYWORDS

Methods with these flags must be of type PyCFunctionWithKeywords. The function expects three parameters: self, args, kwargs where kwargs is a dictionary of all the keyword arguments or possibly NULL if there are no keyword arguments. The parameters are typically processed using PyArg_ParseTupleAndKeywords().

METH_FASTCALL

Fast calling convention supporting only positional arguments. The methods have the type _PyCFunctionFast. The first parameter is self, the second parameter is a C array of PyObject* values indicating the arguments and the third parameter is the number of arguments (the length of the array).

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).

The method needs to be of type PyCMethod, the same as for METH_FASTCALL | METH_KEYWORDS with defining_class argument added after self.

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.

The function must have 2 parameters. Since the second parameter is unused, Py_UNUSED can be used to prevent a compiler warning.

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.

These two constants are not used to indicate the calling convention but the binding when use with methods of classes. These may not be used for functions defined for modules. At most one of these flags may be set for any given method.

METH_CLASS

The method will be passed the type object as the first parameter rather than an instance of the type. This is used to create class methods, similar to what is created when using the classmethod() built-in function.

METH_STATIC

The method will be passed NULL as the first parameter rather than an instance of the type. This is used to create static methods, similar to what is created when using the staticmethod() built-in function.

One other constant controls whether a method is loaded in place of another definition with the same method name.

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.

Accessing attributes of extension types

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 类型

含意

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.

Macro name

C 类型

T_SHORT

short

T_INT

int

T_LONG

长整型

T_FLOAT

float

T_DOUBLE

double

T_STRING

const char

T_OBJECT

PyObject

T_OBJECT_EX

PyObject *

T_CHAR

字符

T_BYTE

字符

T_UBYTE

unsigned char

T_UINT

unsigned int

T_USHORT

unsigned short

T_ULONG

unsigned long

T_BOOL

字符

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:

  1. static PyMemberDef spam_type_members[] = {
  2. {"__dictoffset__", T_PYSSIZET, offsetof(Spam_object, dict), READONLY},
  3. {NULL} /* Sentinel */
  4. };

PyObject *PyMember_GetOne(const char *obj_addr, struct PyMemberDef *m)

Get an attribute belonging to the object at address obj_addr. The attribute is described by PyMemberDef m. Returns NULL on error.

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

Set an attribute belonging to the object at address obj_addr to object o. The attribute to set is described by PyMemberDef m. Returns 0 if successful and a negative value on failure.

type PyGetSetDef

Part of the Stable ABI (including all members).

Structure to define property-like access for a type. See also description of the PyTypeObject.tp_getset slot.

C 类型

含意

名称

const char

attribute name

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

optional docstring

closure

void *

optional function pointer, providing additional data for getter and setter

The get function takes one PyObject* parameter (the instance) and a function pointer (the associated closure):

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

It should return a new reference on success or NULL with a set exception on failure.

set functions take two PyObject* parameters (the instance and the value to be set) and a function pointer (the associated closure):

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

In case the attribute should be deleted the second parameter is NULL. Should return 0 on success or -1 with a set exception on failure.