2. 自定义扩展类型:教程

Python 允许编写 C 扩展模块定义可以从 Python 代码中操纵的新类型,这很像内置的 strlist 类型。所有扩展类型的代码都遵循一个模式,但是在您开始之前,您需要了解一些细节。这份文件是对这个主题介绍。

2.1. 基础

CPython 运行时将所有 Python 对象都视为类型 PyObject* 的变量,即所有 Python 对象的”基础类型”。 PyObject 结构体本身包含了对象的 reference count 和对象的”类型对象”。 类型对象确定解释器需要调用哪些 (C) 函数,例如一个属性查询一个对象,一个方法调用,或者与另一个对象相乘。 这些 C 函数被称为“类型方法”。

所以,如果你想要定义新的扩展类型,需要创建新的类型对象。

这类事情只能用例子解释,这里用一个最小化但完整的的模块,定义了新的类型叫做 Custom 在C扩展模块 custom 里。

注解

这里展示的方法是定义 static 扩展类型的传统方法。可以适合大部分用途。C API也可以定义在堆上分配的扩展类型,使用 PyType_FromSpec() 函数,但不在本入门里讨论。

  1. #define PY_SSIZE_T_CLEAN
  2. #include <Python.h>
  3. typedef struct {
  4. PyObject_HEAD
  5. /* Type-specific fields go here. */
  6. } CustomObject;
  7. static PyTypeObject CustomType = {
  8. PyVarObject_HEAD_INIT(NULL, 0)
  9. .tp_name = "custom.Custom",
  10. .tp_doc = "Custom objects",
  11. .tp_basicsize = sizeof(CustomObject),
  12. .tp_itemsize = 0,
  13. .tp_flags = Py_TPFLAGS_DEFAULT,
  14. .tp_new = PyType_GenericNew,
  15. };
  16. static PyModuleDef custommodule = {
  17. PyModuleDef_HEAD_INIT,
  18. .m_name = "custom",
  19. .m_doc = "Example module that creates an extension type.",
  20. .m_size = -1,
  21. };
  22. PyMODINIT_FUNC
  23. PyInit_custom(void)
  24. {
  25. PyObject *m;
  26. if (PyType_Ready(&CustomType) < 0)
  27. return NULL;
  28. m = PyModule_Create(&custommodule);
  29. if (m == NULL)
  30. return NULL;
  31. Py_INCREF(&CustomType);
  32. if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
  33. Py_DECREF(&CustomType);
  34. Py_DECREF(m);
  35. return NULL;
  36. }
  37. return m;
  38. }

这部分很容易理解,这是为了跟上一章能对接上。这个文件定义了三件事:

  1. Custom 类的对象 object 包含了: CustomObject 结构,这会为每个 Custom 实例分配一次。

  2. Custom type 的行为:这是 CustomType 结构体,其定义了一堆标识和函数指针,会指向解释器里请求的操作。

  3. 初始化 custom 模块: PyInit_custom 函数和对应的 custommodule 结构体。

结构的第一块是

  1. typedef struct {
  2. PyObject_HEAD
  3. } CustomObject;

This is what a Custom object will contain. PyObject_HEAD is mandatory at the start of each object struct and defines a field called ob_base of type PyObject, containing a pointer to a type object and a reference count (these can be accessed using the macros Py_REFCNT and Py_TYPE respectively). The reason for the macro is to abstract away the layout and to enable additional fields in debug builds.

注解

注意在宏 PyObject_HEAD 后没有分号。意外添加分号会导致编译器提示出错。

当然,对象除了在 PyObject_HEAD 存储数据外,还有额外数据;例如,如下定义了标准的Python浮点数:

  1. typedef struct {
  2. PyObject_HEAD
  3. double ob_fval;
  4. } PyFloatObject;

第二个位是类型对象的定义:

  1. static PyTypeObject CustomType = {
  2. PyVarObject_HEAD_INIT(NULL, 0)
  3. .tp_name = "custom.Custom",
  4. .tp_doc = "Custom objects",
  5. .tp_basicsize = sizeof(CustomObject),
  6. .tp_itemsize = 0,
  7. .tp_flags = Py_TPFLAGS_DEFAULT,
  8. .tp_new = PyType_GenericNew,
  9. };

注解

推荐使用如上C99风格的初始化,以避免列出所有的 PyTypeObject 字段,其中很多是你不需要关心的,这样也可以避免关注字段的定义顺序。

object.h 中实际定义的 PyTypeObject 具有比如上定义更多的 字段。 剩余的字段会由 C 编译器用零来填充,通常的做法是不显式地指定它们,除非你确实需要它们。

我们先挑选一部分,每次一个字段:

  1. PyVarObject_HEAD_INIT(NULL, 0)

这一行是强制的样板,用以初始化如上提到的 ob_base 字段:

  1. .tp_name = "custom.Custom",

我们的类型的名称。 这将出现在我们的对象的默认文本表示形式和某些错误消息中,例如:

  1. >>> "" + custom.Custom()
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. TypeError: can only concatenate str (not "custom.Custom") to str

Note that the name is a dotted name that includes both the module name and the name of the type within the module. The module in this case is custom and the type is Custom, so we set the type name to custom.Custom. Using the real dotted import path is important to make your type compatible with the pydoc and pickle modules.

  1. .tp_basicsize = sizeof(CustomObject),
  2. .tp_itemsize = 0,

This is so that Python knows how much memory to allocate when creating new Custom instances. tp_itemsize is only used for variable-sized objects and should otherwise be zero.

注解

If you want your type to be subclassable from Python, and your type has the same tp_basicsize as its base type, you may have problems with multiple inheritance. A Python subclass of your type will have to list your type first in its __bases__, or else it will not be able to call your type’s __new__() method without getting an error. You can avoid this problem by ensuring that your type has a larger value for tp_basicsize than its base type does. Most of the time, this will be true anyway, because either your base type will be object, or else you will be adding data members to your base type, and therefore increasing its size.

We set the class flags to Py_TPFLAGS_DEFAULT.

  1. .tp_flags = Py_TPFLAGS_DEFAULT,

All types should include this constant in their flags. It enables all of the members defined until at least Python 3.3. If you need further members, you will need to OR the corresponding flags.

We provide a doc string for the type in tp_doc.

  1. .tp_doc = "Custom objects",

To enable object creation, we have to provide a tp_new handler. This is the equivalent of the Python method __new__(), but has to be specified explicitly. In this case, we can just use the default implementation provided by the API function PyType_GenericNew().

  1. .tp_new = PyType_GenericNew,

Everything else in the file should be familiar, except for some code in PyInit_custom():

  1. if (PyType_Ready(&CustomType) < 0)
  2. return;

This initializes the Custom type, filling in a number of members to the appropriate default values, including ob_type that we initially set to NULL.

  1. Py_INCREF(&CustomType);
  2. if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
  3. Py_DECREF(&CustomType);
  4. Py_DECREF(m);
  5. return NULL;
  6. }

This adds the type to the module dictionary. This allows us to create Custom instances by calling the Custom class:

  1. >>> import custom
  2. >>> mycustom = custom.Custom()

That’s it! All that remains is to build it; put the above code in a file called custom.c and:

  1. from distutils.core import setup, Extension
  2. setup(name="custom", version="1.0",
  3. ext_modules=[Extension("custom", ["custom.c"])])

in a file called setup.py; then typing

  1. $ python setup.py build

at a shell should produce a file custom.so in a subdirectory; move to that directory and fire up Python —- you should be able to import custom and play around with Custom objects.

这并不难,对吗?

Of course, the current Custom type is pretty uninteresting. It has no data and doesn’t do anything. It can’t even be subclassed.

注解

While this documentation showcases the standard distutils module for building C extensions, it is recommended in real-world use cases to use the newer and better-maintained setuptools library. Documentation on how to do this is out of scope for this document and can be found in the Python Packaging User’s Guide.

2.2. Adding data and methods to the Basic example

Let’s extend the basic example to add some data and methods. Let’s also make the type usable as a base class. We’ll create a new module, custom2 that adds these capabilities:

  1. #define PY_SSIZE_T_CLEAN
  2. #include <Python.h>
  3. #include "structmember.h"
  4. typedef struct {
  5. PyObject_HEAD
  6. PyObject *first; /* first name */
  7. PyObject *last; /* last name */
  8. int number;
  9. } CustomObject;
  10. static void
  11. Custom_dealloc(CustomObject *self)
  12. {
  13. Py_XDECREF(self->first);
  14. Py_XDECREF(self->last);
  15. Py_TYPE(self)->tp_free((PyObject *) self);
  16. }
  17. static PyObject *
  18. Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  19. {
  20. CustomObject *self;
  21. self = (CustomObject *) type->tp_alloc(type, 0);
  22. if (self != NULL) {
  23. self->first = PyUnicode_FromString("");
  24. if (self->first == NULL) {
  25. Py_DECREF(self);
  26. return NULL;
  27. }
  28. self->last = PyUnicode_FromString("");
  29. if (self->last == NULL) {
  30. Py_DECREF(self);
  31. return NULL;
  32. }
  33. self->number = 0;
  34. }
  35. return (PyObject *) self;
  36. }
  37. static int
  38. Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
  39. {
  40. static char *kwlist[] = {"first", "last", "number", NULL};
  41. PyObject *first = NULL, *last = NULL, *tmp;
  42. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
  43. &first, &last,
  44. &self->number))
  45. return -1;
  46. if (first) {
  47. tmp = self->first;
  48. Py_INCREF(first);
  49. self->first = first;
  50. Py_XDECREF(tmp);
  51. }
  52. if (last) {
  53. tmp = self->last;
  54. Py_INCREF(last);
  55. self->last = last;
  56. Py_XDECREF(tmp);
  57. }
  58. return 0;
  59. }
  60. static PyMemberDef Custom_members[] = {
  61. {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
  62. "first name"},
  63. {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
  64. "last name"},
  65. {"number", T_INT, offsetof(CustomObject, number), 0,
  66. "custom number"},
  67. {NULL} /* Sentinel */
  68. };
  69. static PyObject *
  70. Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
  71. {
  72. if (self->first == NULL) {
  73. PyErr_SetString(PyExc_AttributeError, "first");
  74. return NULL;
  75. }
  76. if (self->last == NULL) {
  77. PyErr_SetString(PyExc_AttributeError, "last");
  78. return NULL;
  79. }
  80. return PyUnicode_FromFormat("%S %S", self->first, self->last);
  81. }
  82. static PyMethodDef Custom_methods[] = {
  83. {"name", (PyCFunction) Custom_name, METH_NOARGS,
  84. "Return the name, combining the first and last name"
  85. },
  86. {NULL} /* Sentinel */
  87. };
  88. static PyTypeObject CustomType = {
  89. PyVarObject_HEAD_INIT(NULL, 0)
  90. .tp_name = "custom2.Custom",
  91. .tp_doc = "Custom objects",
  92. .tp_basicsize = sizeof(CustomObject),
  93. .tp_itemsize = 0,
  94. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  95. .tp_new = Custom_new,
  96. .tp_init = (initproc) Custom_init,
  97. .tp_dealloc = (destructor) Custom_dealloc,
  98. .tp_members = Custom_members,
  99. .tp_methods = Custom_methods,
  100. };
  101. static PyModuleDef custommodule = {
  102. PyModuleDef_HEAD_INIT,
  103. .m_name = "custom2",
  104. .m_doc = "Example module that creates an extension type.",
  105. .m_size = -1,
  106. };
  107. PyMODINIT_FUNC
  108. PyInit_custom2(void)
  109. {
  110. PyObject *m;
  111. if (PyType_Ready(&CustomType) < 0)
  112. return NULL;
  113. m = PyModule_Create(&custommodule);
  114. if (m == NULL)
  115. return NULL;
  116. Py_INCREF(&CustomType);
  117. if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
  118. Py_DECREF(&CustomType);
  119. Py_DECREF(m);
  120. return NULL;
  121. }
  122. return m;
  123. }

This version of the module has a number of changes.

We’ve added an extra include:

  1. #include <structmember.h>

This include provides declarations that we use to handle attributes, as described a bit later.

The Custom type now has three data attributes in its C struct, first, last, and number. The first and last variables are Python strings containing first and last names. The number attribute is a C integer.

The object structure is updated accordingly:

  1. typedef struct {
  2. PyObject_HEAD
  3. PyObject *first; /* first name */
  4. PyObject *last; /* last name */
  5. int number;
  6. } CustomObject;

Because we now have data to manage, we have to be more careful about object allocation and deallocation. At a minimum, we need a deallocation method:

  1. static void
  2. Custom_dealloc(CustomObject *self)
  3. {
  4. Py_XDECREF(self->first);
  5. Py_XDECREF(self->last);
  6. Py_TYPE(self)->tp_free((PyObject *) self);
  7. }

which is assigned to the tp_dealloc member:

  1. .tp_dealloc = (destructor) Custom_dealloc,

This method first clears the reference counts of the two Python attributes. Py_XDECREF() correctly handles the case where its argument is NULL (which might happen here if tp_new failed midway). It then calls the tp_free member of the object’s type (computed by Py_TYPE(self)) to free the object’s memory. Note that the object’s type might not be CustomType, because the object may be an instance of a subclass.

注解

The explicit cast to destructor above is needed because we defined Custom_dealloc to take a CustomObject * argument, but the tp_dealloc function pointer expects to receive a PyObject * argument. Otherwise, the compiler will emit a warning. This is object-oriented polymorphism, in C!

We want to make sure that the first and last names are initialized to empty strings, so we provide a tp_new implementation:

  1. static PyObject *
  2. Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  3. {
  4. CustomObject *self;
  5. self = (CustomObject *) type->tp_alloc(type, 0);
  6. if (self != NULL) {
  7. self->first = PyUnicode_FromString("");
  8. if (self->first == NULL) {
  9. Py_DECREF(self);
  10. return NULL;
  11. }
  12. self->last = PyUnicode_FromString("");
  13. if (self->last == NULL) {
  14. Py_DECREF(self);
  15. return NULL;
  16. }
  17. self->number = 0;
  18. }
  19. return (PyObject *) self;
  20. }

and install it in the tp_new member:

  1. .tp_new = Custom_new,

The tp_new handler is responsible for creating (as opposed to initializing) objects of the type. It is exposed in Python as the __new__() method. It is not required to define a tp_new member, and indeed many extension types will simply reuse PyType_GenericNew() as done in the first version of the Custom type above. In this case, we use the tp_new handler to initialize the first and last attributes to non-NULL default values.

tp_new is passed the type being instantiated (not necessarily CustomType, if a subclass is instantiated) and any arguments passed when the type was called, and is expected to return the instance created. tp_new handlers always accept positional and keyword arguments, but they often ignore the arguments, leaving the argument handling to initializer (a.k.a. tp_init in C or __init__ in Python) methods.

注解

tp_new shouldn’t call tp_init explicitly, as the interpreter will do it itself.

The tp_new implementation calls the tp_alloc slot to allocate memory:

  1. self = (CustomObject *) type->tp_alloc(type, 0);

Since memory allocation may fail, we must check the tp_alloc result against NULL before proceeding.

注解

We didn’t fill the tp_alloc slot ourselves. Rather PyType_Ready() fills it for us by inheriting it from our base class, which is object by default. Most types use the default allocation strategy.

注解

If you are creating a co-operative tp_new (one that calls a base type’s tp_new or __new__()), you must not try to determine what method to call using method resolution order at runtime. Always statically determine what type you are going to call, and call its tp_new directly, or via type->tp_base->tp_new. If you do not do this, Python subclasses of your type that also inherit from other Python-defined classes may not work correctly. (Specifically, you may not be able to create instances of such subclasses without getting a TypeError.)

We also define an initialization function which accepts arguments to provide initial values for our instance:

  1. static int
  2. Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
  3. {
  4. static char *kwlist[] = {"first", "last", "number", NULL};
  5. PyObject *first = NULL, *last = NULL, *tmp;
  6. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
  7. &first, &last,
  8. &self->number))
  9. return -1;
  10. if (first) {
  11. tmp = self->first;
  12. Py_INCREF(first);
  13. self->first = first;
  14. Py_XDECREF(tmp);
  15. }
  16. if (last) {
  17. tmp = self->last;
  18. Py_INCREF(last);
  19. self->last = last;
  20. Py_XDECREF(tmp);
  21. }
  22. return 0;
  23. }

by filling the tp_init slot.

  1. .tp_init = (initproc) Custom_init,

The tp_init slot is exposed in Python as the __init__() method. It is used to initialize an object after it’s created. Initializers always accept positional and keyword arguments, and they should return either 0 on success or -1 on error.

Unlike the tp_new handler, there is no guarantee that tp_init is called at all (for example, the pickle module by default doesn’t call __init__() on unpickled instances). It can also be called multiple times. Anyone can call the __init__() method on our objects. For this reason, we have to be extra careful when assigning the new attribute values. We might be tempted, for example to assign the first member like this:

  1. if (first) {
  2. Py_XDECREF(self->first);
  3. Py_INCREF(first);
  4. self->first = first;
  5. }

But this would be risky. Our type doesn’t restrict the type of the first member, so it could be any kind of object. It could have a destructor that causes code to be executed that tries to access the first member; or that destructor could release the Global interpreter Lock and let arbitrary code run in other threads that accesses and modifies our object.

To be paranoid and protect ourselves against this possibility, we almost always reassign members before decrementing their reference counts. When don’t we have to do this?

  • when we absolutely know that the reference count is greater than 1;

  • when we know that deallocation of the object 1 will neither release the GIL nor cause any calls back into our type’s code;

  • when decrementing a reference count in a tp_dealloc handler on a type which doesn’t support cyclic garbage collection 2.

We want to expose our instance variables as attributes. There are a number of ways to do that. The simplest way is to define member definitions:

  1. static PyMemberDef Custom_members[] = {
  2. {"first", T_OBJECT_EX, offsetof(CustomObject, first), 0,
  3. "first name"},
  4. {"last", T_OBJECT_EX, offsetof(CustomObject, last), 0,
  5. "last name"},
  6. {"number", T_INT, offsetof(CustomObject, number), 0,
  7. "custom number"},
  8. {NULL} /* Sentinel */
  9. };

and put the definitions in the tp_members slot:

  1. .tp_members = Custom_members,

Each member definition has a member name, type, offset, access flags and documentation string. See the 泛型属性管理 section below for details.

A disadvantage of this approach is that it doesn’t provide a way to restrict the types of objects that can be assigned to the Python attributes. We expect the first and last names to be strings, but any Python objects can be assigned. Further, the attributes can be deleted, setting the C pointers to NULL. Even though we can make sure the members are initialized to non-NULL values, the members can be set to NULL if the attributes are deleted.

We define a single method, Custom.name(), that outputs the objects name as the concatenation of the first and last names.

  1. static PyObject *
  2. Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
  3. {
  4. if (self->first == NULL) {
  5. PyErr_SetString(PyExc_AttributeError, "first");
  6. return NULL;
  7. }
  8. if (self->last == NULL) {
  9. PyErr_SetString(PyExc_AttributeError, "last");
  10. return NULL;
  11. }
  12. return PyUnicode_FromFormat("%S %S", self->first, self->last);
  13. }

The method is implemented as a C function that takes a Custom (or Custom subclass) instance as the first argument. Methods always take an instance as the first argument. Methods often take positional and keyword arguments as well, but in this case we don’t take any and don’t need to accept a positional argument tuple or keyword argument dictionary. This method is equivalent to the Python method:

  1. def name(self):
  2. return "%s %s" % (self.first, self.last)

Note that we have to check for the possibility that our first and last members are NULL. This is because they can be deleted, in which case they are set to NULL. It would be better to prevent deletion of these attributes and to restrict the attribute values to be strings. We’ll see how to do that in the next section.

Now that we’ve defined the method, we need to create an array of method definitions:

  1. static PyMethodDef Custom_methods[] = {
  2. {"name", (PyCFunction) Custom_name, METH_NOARGS,
  3. "Return the name, combining the first and last name"
  4. },
  5. {NULL} /* Sentinel */
  6. };

(note that we used the METH_NOARGS flag to indicate that the method is expecting no arguments other than self)

and assign it to the tp_methods slot:

  1. .tp_methods = Custom_methods,

Finally, we’ll make our type usable as a base class for subclassing. We’ve written our methods carefully so far so that they don’t make any assumptions about the type of the object being created or used, so all we need to do is to add the Py_TPFLAGS_BASETYPE to our class flag definition:

  1. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

We rename PyInit_custom() to PyInit_custom2(), update the module name in the PyModuleDef struct, and update the full class name in the PyTypeObject struct.

Finally, we update our setup.py file to build the new module:

  1. from distutils.core import setup, Extension
  2. setup(name="custom", version="1.0",
  3. ext_modules=[
  4. Extension("custom", ["custom.c"]),
  5. Extension("custom2", ["custom2.c"]),
  6. ])

2.3. Providing finer control over data attributes

In this section, we’ll provide finer control over how the first and last attributes are set in the Custom example. In the previous version of our module, the instance variables first and last could be set to non-string values or even deleted. We want to make sure that these attributes always contain strings.

  1. #define PY_SSIZE_T_CLEAN
  2. #include <Python.h>
  3. #include "structmember.h"
  4. typedef struct {
  5. PyObject_HEAD
  6. PyObject *first; /* first name */
  7. PyObject *last; /* last name */
  8. int number;
  9. } CustomObject;
  10. static void
  11. Custom_dealloc(CustomObject *self)
  12. {
  13. Py_XDECREF(self->first);
  14. Py_XDECREF(self->last);
  15. Py_TYPE(self)->tp_free((PyObject *) self);
  16. }
  17. static PyObject *
  18. Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  19. {
  20. CustomObject *self;
  21. self = (CustomObject *) type->tp_alloc(type, 0);
  22. if (self != NULL) {
  23. self->first = PyUnicode_FromString("");
  24. if (self->first == NULL) {
  25. Py_DECREF(self);
  26. return NULL;
  27. }
  28. self->last = PyUnicode_FromString("");
  29. if (self->last == NULL) {
  30. Py_DECREF(self);
  31. return NULL;
  32. }
  33. self->number = 0;
  34. }
  35. return (PyObject *) self;
  36. }
  37. static int
  38. Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
  39. {
  40. static char *kwlist[] = {"first", "last", "number", NULL};
  41. PyObject *first = NULL, *last = NULL, *tmp;
  42. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
  43. &first, &last,
  44. &self->number))
  45. return -1;
  46. if (first) {
  47. tmp = self->first;
  48. Py_INCREF(first);
  49. self->first = first;
  50. Py_DECREF(tmp);
  51. }
  52. if (last) {
  53. tmp = self->last;
  54. Py_INCREF(last);
  55. self->last = last;
  56. Py_DECREF(tmp);
  57. }
  58. return 0;
  59. }
  60. static PyMemberDef Custom_members[] = {
  61. {"number", T_INT, offsetof(CustomObject, number), 0,
  62. "custom number"},
  63. {NULL} /* Sentinel */
  64. };
  65. static PyObject *
  66. Custom_getfirst(CustomObject *self, void *closure)
  67. {
  68. Py_INCREF(self->first);
  69. return self->first;
  70. }
  71. static int
  72. Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
  73. {
  74. PyObject *tmp;
  75. if (value == NULL) {
  76. PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
  77. return -1;
  78. }
  79. if (!PyUnicode_Check(value)) {
  80. PyErr_SetString(PyExc_TypeError,
  81. "The first attribute value must be a string");
  82. return -1;
  83. }
  84. tmp = self->first;
  85. Py_INCREF(value);
  86. self->first = value;
  87. Py_DECREF(tmp);
  88. return 0;
  89. }
  90. static PyObject *
  91. Custom_getlast(CustomObject *self, void *closure)
  92. {
  93. Py_INCREF(self->last);
  94. return self->last;
  95. }
  96. static int
  97. Custom_setlast(CustomObject *self, PyObject *value, void *closure)
  98. {
  99. PyObject *tmp;
  100. if (value == NULL) {
  101. PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
  102. return -1;
  103. }
  104. if (!PyUnicode_Check(value)) {
  105. PyErr_SetString(PyExc_TypeError,
  106. "The last attribute value must be a string");
  107. return -1;
  108. }
  109. tmp = self->last;
  110. Py_INCREF(value);
  111. self->last = value;
  112. Py_DECREF(tmp);
  113. return 0;
  114. }
  115. static PyGetSetDef Custom_getsetters[] = {
  116. {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
  117. "first name", NULL},
  118. {"last", (getter) Custom_getlast, (setter) Custom_setlast,
  119. "last name", NULL},
  120. {NULL} /* Sentinel */
  121. };
  122. static PyObject *
  123. Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
  124. {
  125. return PyUnicode_FromFormat("%S %S", self->first, self->last);
  126. }
  127. static PyMethodDef Custom_methods[] = {
  128. {"name", (PyCFunction) Custom_name, METH_NOARGS,
  129. "Return the name, combining the first and last name"
  130. },
  131. {NULL} /* Sentinel */
  132. };
  133. static PyTypeObject CustomType = {
  134. PyVarObject_HEAD_INIT(NULL, 0)
  135. .tp_name = "custom3.Custom",
  136. .tp_doc = "Custom objects",
  137. .tp_basicsize = sizeof(CustomObject),
  138. .tp_itemsize = 0,
  139. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  140. .tp_new = Custom_new,
  141. .tp_init = (initproc) Custom_init,
  142. .tp_dealloc = (destructor) Custom_dealloc,
  143. .tp_members = Custom_members,
  144. .tp_methods = Custom_methods,
  145. .tp_getset = Custom_getsetters,
  146. };
  147. static PyModuleDef custommodule = {
  148. PyModuleDef_HEAD_INIT,
  149. .m_name = "custom3",
  150. .m_doc = "Example module that creates an extension type.",
  151. .m_size = -1,
  152. };
  153. PyMODINIT_FUNC
  154. PyInit_custom3(void)
  155. {
  156. PyObject *m;
  157. if (PyType_Ready(&CustomType) < 0)
  158. return NULL;
  159. m = PyModule_Create(&custommodule);
  160. if (m == NULL)
  161. return NULL;
  162. Py_INCREF(&CustomType);
  163. if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
  164. Py_DECREF(&CustomType);
  165. Py_DECREF(m);
  166. return NULL;
  167. }
  168. return m;
  169. }

To provide greater control, over the first and last attributes, we’ll use custom getter and setter functions. Here are the functions for getting and setting the first attribute:

  1. static PyObject *
  2. Custom_getfirst(CustomObject *self, void *closure)
  3. {
  4. Py_INCREF(self->first);
  5. return self->first;
  6. }
  7. static int
  8. Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
  9. {
  10. PyObject *tmp;
  11. if (value == NULL) {
  12. PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
  13. return -1;
  14. }
  15. if (!PyUnicode_Check(value)) {
  16. PyErr_SetString(PyExc_TypeError,
  17. "The first attribute value must be a string");
  18. return -1;
  19. }
  20. tmp = self->first;
  21. Py_INCREF(value);
  22. self->first = value;
  23. Py_DECREF(tmp);
  24. return 0;
  25. }

The getter function is passed a Custom object and a “closure”, which is a void pointer. In this case, the closure is ignored. (The closure supports an advanced usage in which definition data is passed to the getter and setter. This could, for example, be used to allow a single set of getter and setter functions that decide the attribute to get or set based on data in the closure.)

The setter function is passed the Custom object, the new value, and the closure. The new value may be NULL, in which case the attribute is being deleted. In our setter, we raise an error if the attribute is deleted or if its new value is not a string.

We create an array of PyGetSetDef structures:

  1. static PyGetSetDef Custom_getsetters[] = {
  2. {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
  3. "first name", NULL},
  4. {"last", (getter) Custom_getlast, (setter) Custom_setlast,
  5. "last name", NULL},
  6. {NULL} /* Sentinel */
  7. };

and register it in the tp_getset slot:

  1. .tp_getset = Custom_getsetters,

The last item in a PyGetSetDef structure is the “closure” mentioned above. In this case, we aren’t using a closure, so we just pass NULL.

We also remove the member definitions for these attributes:

  1. static PyMemberDef Custom_members[] = {
  2. {"number", T_INT, offsetof(CustomObject, number), 0,
  3. "custom number"},
  4. {NULL} /* Sentinel */
  5. };

We also need to update the tp_init handler to only allow strings 3 to be passed:

  1. static int
  2. Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
  3. {
  4. static char *kwlist[] = {"first", "last", "number", NULL};
  5. PyObject *first = NULL, *last = NULL, *tmp;
  6. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
  7. &first, &last,
  8. &self->number))
  9. return -1;
  10. if (first) {
  11. tmp = self->first;
  12. Py_INCREF(first);
  13. self->first = first;
  14. Py_DECREF(tmp);
  15. }
  16. if (last) {
  17. tmp = self->last;
  18. Py_INCREF(last);
  19. self->last = last;
  20. Py_DECREF(tmp);
  21. }
  22. return 0;
  23. }

With these changes, we can assure that the first and last members are never NULL so we can remove checks for NULL values in almost all cases. This means that most of the Py_XDECREF() calls can be converted to Py_DECREF() calls. The only place we can’t change these calls is in the tp_dealloc implementation, where there is the possibility that the initialization of these members failed in tp_new.

We also rename the module initialization function and module name in the initialization function, as we did before, and we add an extra definition to the setup.py file.

2.4. Supporting cyclic garbage collection

Python has a cyclic garbage collector (GC) that can identify unneeded objects even when their reference counts are not zero. This can happen when objects are involved in cycles. For example, consider:

  1. >>> l = []
  2. >>> l.append(l)
  3. >>> del l

In this example, we create a list that contains itself. When we delete it, it still has a reference from itself. Its reference count doesn’t drop to zero. Fortunately, Python’s cyclic garbage collector will eventually figure out that the list is garbage and free it.

In the second version of the Custom example, we allowed any kind of object to be stored in the first or last attributes 4. Besides, in the second and third versions, we allowed subclassing Custom, and subclasses may add arbitrary attributes. For any of those two reasons, Custom objects can participate in cycles:

  1. >>> import custom3
  2. >>> class Derived(custom3.Custom): pass
  3. ...
  4. >>> n = Derived()
  5. >>> n.some_attribute = n

To allow a Custom instance participating in a reference cycle to be properly detected and collected by the cyclic GC, our Custom type needs to fill two additional slots and to enable a flag that enables these slots:

  1. #define PY_SSIZE_T_CLEAN
  2. #include <Python.h>
  3. #include "structmember.h"
  4. typedef struct {
  5. PyObject_HEAD
  6. PyObject *first; /* first name */
  7. PyObject *last; /* last name */
  8. int number;
  9. } CustomObject;
  10. static int
  11. Custom_traverse(CustomObject *self, visitproc visit, void *arg)
  12. {
  13. Py_VISIT(self->first);
  14. Py_VISIT(self->last);
  15. return 0;
  16. }
  17. static int
  18. Custom_clear(CustomObject *self)
  19. {
  20. Py_CLEAR(self->first);
  21. Py_CLEAR(self->last);
  22. return 0;
  23. }
  24. static void
  25. Custom_dealloc(CustomObject *self)
  26. {
  27. PyObject_GC_UnTrack(self);
  28. Custom_clear(self);
  29. Py_TYPE(self)->tp_free((PyObject *) self);
  30. }
  31. static PyObject *
  32. Custom_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  33. {
  34. CustomObject *self;
  35. self = (CustomObject *) type->tp_alloc(type, 0);
  36. if (self != NULL) {
  37. self->first = PyUnicode_FromString("");
  38. if (self->first == NULL) {
  39. Py_DECREF(self);
  40. return NULL;
  41. }
  42. self->last = PyUnicode_FromString("");
  43. if (self->last == NULL) {
  44. Py_DECREF(self);
  45. return NULL;
  46. }
  47. self->number = 0;
  48. }
  49. return (PyObject *) self;
  50. }
  51. static int
  52. Custom_init(CustomObject *self, PyObject *args, PyObject *kwds)
  53. {
  54. static char *kwlist[] = {"first", "last", "number", NULL};
  55. PyObject *first = NULL, *last = NULL, *tmp;
  56. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|UUi", kwlist,
  57. &first, &last,
  58. &self->number))
  59. return -1;
  60. if (first) {
  61. tmp = self->first;
  62. Py_INCREF(first);
  63. self->first = first;
  64. Py_DECREF(tmp);
  65. }
  66. if (last) {
  67. tmp = self->last;
  68. Py_INCREF(last);
  69. self->last = last;
  70. Py_DECREF(tmp);
  71. }
  72. return 0;
  73. }
  74. static PyMemberDef Custom_members[] = {
  75. {"number", T_INT, offsetof(CustomObject, number), 0,
  76. "custom number"},
  77. {NULL} /* Sentinel */
  78. };
  79. static PyObject *
  80. Custom_getfirst(CustomObject *self, void *closure)
  81. {
  82. Py_INCREF(self->first);
  83. return self->first;
  84. }
  85. static int
  86. Custom_setfirst(CustomObject *self, PyObject *value, void *closure)
  87. {
  88. if (value == NULL) {
  89. PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
  90. return -1;
  91. }
  92. if (!PyUnicode_Check(value)) {
  93. PyErr_SetString(PyExc_TypeError,
  94. "The first attribute value must be a string");
  95. return -1;
  96. }
  97. Py_INCREF(value);
  98. Py_CLEAR(self->first);
  99. self->first = value;
  100. return 0;
  101. }
  102. static PyObject *
  103. Custom_getlast(CustomObject *self, void *closure)
  104. {
  105. Py_INCREF(self->last);
  106. return self->last;
  107. }
  108. static int
  109. Custom_setlast(CustomObject *self, PyObject *value, void *closure)
  110. {
  111. if (value == NULL) {
  112. PyErr_SetString(PyExc_TypeError, "Cannot delete the last attribute");
  113. return -1;
  114. }
  115. if (!PyUnicode_Check(value)) {
  116. PyErr_SetString(PyExc_TypeError,
  117. "The last attribute value must be a string");
  118. return -1;
  119. }
  120. Py_INCREF(value);
  121. Py_CLEAR(self->last);
  122. self->last = value;
  123. return 0;
  124. }
  125. static PyGetSetDef Custom_getsetters[] = {
  126. {"first", (getter) Custom_getfirst, (setter) Custom_setfirst,
  127. "first name", NULL},
  128. {"last", (getter) Custom_getlast, (setter) Custom_setlast,
  129. "last name", NULL},
  130. {NULL} /* Sentinel */
  131. };
  132. static PyObject *
  133. Custom_name(CustomObject *self, PyObject *Py_UNUSED(ignored))
  134. {
  135. return PyUnicode_FromFormat("%S %S", self->first, self->last);
  136. }
  137. static PyMethodDef Custom_methods[] = {
  138. {"name", (PyCFunction) Custom_name, METH_NOARGS,
  139. "Return the name, combining the first and last name"
  140. },
  141. {NULL} /* Sentinel */
  142. };
  143. static PyTypeObject CustomType = {
  144. PyVarObject_HEAD_INIT(NULL, 0)
  145. .tp_name = "custom4.Custom",
  146. .tp_doc = "Custom objects",
  147. .tp_basicsize = sizeof(CustomObject),
  148. .tp_itemsize = 0,
  149. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,
  150. .tp_new = Custom_new,
  151. .tp_init = (initproc) Custom_init,
  152. .tp_dealloc = (destructor) Custom_dealloc,
  153. .tp_traverse = (traverseproc) Custom_traverse,
  154. .tp_clear = (inquiry) Custom_clear,
  155. .tp_members = Custom_members,
  156. .tp_methods = Custom_methods,
  157. .tp_getset = Custom_getsetters,
  158. };
  159. static PyModuleDef custommodule = {
  160. PyModuleDef_HEAD_INIT,
  161. .m_name = "custom4",
  162. .m_doc = "Example module that creates an extension type.",
  163. .m_size = -1,
  164. };
  165. PyMODINIT_FUNC
  166. PyInit_custom4(void)
  167. {
  168. PyObject *m;
  169. if (PyType_Ready(&CustomType) < 0)
  170. return NULL;
  171. m = PyModule_Create(&custommodule);
  172. if (m == NULL)
  173. return NULL;
  174. Py_INCREF(&CustomType);
  175. if (PyModule_AddObject(m, "Custom", (PyObject *) &CustomType) < 0) {
  176. Py_DECREF(&CustomType);
  177. Py_DECREF(m);
  178. return NULL;
  179. }
  180. return m;
  181. }

First, the traversal method lets the cyclic GC know about subobjects that could participate in cycles:

  1. static int
  2. Custom_traverse(CustomObject *self, visitproc visit, void *arg)
  3. {
  4. int vret;
  5. if (self->first) {
  6. vret = visit(self->first, arg);
  7. if (vret != 0)
  8. return vret;
  9. }
  10. if (self->last) {
  11. vret = visit(self->last, arg);
  12. if (vret != 0)
  13. return vret;
  14. }
  15. return 0;
  16. }

For each subobject that can participate in cycles, we need to call the visit() function, which is passed to the traversal method. The visit() function takes as arguments the subobject and the extra argument arg passed to the traversal method. It returns an integer value that must be returned if it is non-zero.

Python provides a Py_VISIT() macro that automates calling visit functions. With Py_VISIT(), we can minimize the amount of boilerplate in Custom_traverse:

  1. static int
  2. Custom_traverse(CustomObject *self, visitproc visit, void *arg)
  3. {
  4. Py_VISIT(self->first);
  5. Py_VISIT(self->last);
  6. return 0;
  7. }

注解

The tp_traverse implementation must name its arguments exactly visit and arg in order to use Py_VISIT().

Second, we need to provide a method for clearing any subobjects that can participate in cycles:

  1. static int
  2. Custom_clear(CustomObject *self)
  3. {
  4. Py_CLEAR(self->first);
  5. Py_CLEAR(self->last);
  6. return 0;
  7. }

Notice the use of the Py_CLEAR() macro. It is the recommended and safe way to clear data attributes of arbitrary types while decrementing their reference counts. If you were to call Py_XDECREF() instead on the attribute before setting it to NULL, there is a possibility that the attribute’s destructor would call back into code that reads the attribute again (especially if there is a reference cycle).

注解

You could emulate Py_CLEAR() by writing:

  1. PyObject *tmp;
  2. tmp = self->first;
  3. self->first = NULL;
  4. Py_XDECREF(tmp);

Nevertheless, it is much easier and less error-prone to always use Py_CLEAR() when deleting an attribute. Don’t try to micro-optimize at the expense of robustness!

The deallocator Custom_dealloc may call arbitrary code when clearing attributes. It means the circular GC can be triggered inside the function. Since the GC assumes reference count is not zero, we need to untrack the object from the GC by calling PyObject_GC_UnTrack() before clearing members. Here is our reimplemented deallocator using PyObject_GC_UnTrack() and Custom_clear:

  1. static void
  2. Custom_dealloc(CustomObject *self)
  3. {
  4. PyObject_GC_UnTrack(self);
  5. Custom_clear(self);
  6. Py_TYPE(self)->tp_free((PyObject *) self);
  7. }

Finally, we add the Py_TPFLAGS_HAVE_GC flag to the class flags:

  1. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC,

That’s pretty much it. If we had written custom tp_alloc or tp_free handlers, we’d need to modify them for cyclic garbage collection. Most extensions will use the versions automatically provided.

2.5. Subclassing other types

It is possible to create new extension types that are derived from existing types. It is easiest to inherit from the built in types, since an extension can easily use the PyTypeObject it needs. It can be difficult to share these PyTypeObject structures between extension modules.

In this example we will create a SubList type that inherits from the built-in list type. The new type will be completely compatible with regular lists, but will have an additional increment() method that increases an internal counter:

  1. >>> import sublist
  2. >>> s = sublist.SubList(range(3))
  3. >>> s.extend(s)
  4. >>> print(len(s))
  5. 6
  6. >>> print(s.increment())
  7. 1
  8. >>> print(s.increment())
  9. 2
  1. #define PY_SSIZE_T_CLEAN
  2. #include <Python.h>
  3. typedef struct {
  4. PyListObject list;
  5. int state;
  6. } SubListObject;
  7. static PyObject *
  8. SubList_increment(SubListObject *self, PyObject *unused)
  9. {
  10. self->state++;
  11. return PyLong_FromLong(self->state);
  12. }
  13. static PyMethodDef SubList_methods[] = {
  14. {"increment", (PyCFunction) SubList_increment, METH_NOARGS,
  15. PyDoc_STR("increment state counter")},
  16. {NULL},
  17. };
  18. static int
  19. SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
  20. {
  21. if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
  22. return -1;
  23. self->state = 0;
  24. return 0;
  25. }
  26. static PyTypeObject SubListType = {
  27. PyVarObject_HEAD_INIT(NULL, 0)
  28. .tp_name = "sublist.SubList",
  29. .tp_doc = "SubList objects",
  30. .tp_basicsize = sizeof(SubListObject),
  31. .tp_itemsize = 0,
  32. .tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
  33. .tp_init = (initproc) SubList_init,
  34. .tp_methods = SubList_methods,
  35. };
  36. static PyModuleDef sublistmodule = {
  37. PyModuleDef_HEAD_INIT,
  38. .m_name = "sublist",
  39. .m_doc = "Example module that creates an extension type.",
  40. .m_size = -1,
  41. };
  42. PyMODINIT_FUNC
  43. PyInit_sublist(void)
  44. {
  45. PyObject *m;
  46. SubListType.tp_base = &PyList_Type;
  47. if (PyType_Ready(&SubListType) < 0)
  48. return NULL;
  49. m = PyModule_Create(&sublistmodule);
  50. if (m == NULL)
  51. return NULL;
  52. Py_INCREF(&SubListType);
  53. if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
  54. Py_DECREF(&SubListType);
  55. Py_DECREF(m);
  56. return NULL;
  57. }
  58. return m;
  59. }

As you can see, the source code closely resembles the Custom examples in previous sections. We will break down the main differences between them.

  1. typedef struct {
  2. PyListObject list;
  3. int state;
  4. } SubListObject;

The primary difference for derived type objects is that the base type’s object structure must be the first value. The base type will already include the PyObject_HEAD() at the beginning of its structure.

When a Python object is a SubList instance, its PyObject * pointer can be safely cast to both PyListObject * and SubListObject *:

  1. static int
  2. SubList_init(SubListObject *self, PyObject *args, PyObject *kwds)
  3. {
  4. if (PyList_Type.tp_init((PyObject *) self, args, kwds) < 0)
  5. return -1;
  6. self->state = 0;
  7. return 0;
  8. }

We see above how to call through to the __init__ method of the base type.

This pattern is important when writing a type with custom tp_new and tp_dealloc members. The tp_new handler should not actually create the memory for the object with its tp_alloc, but let the base class handle it by calling its own tp_new.

The PyTypeObject struct supports a tp_base specifying the type’s concrete base class. Due to cross-platform compiler issues, you can’t fill that field directly with a reference to PyList_Type; it should be done later in the module initialization function:

  1. PyMODINIT_FUNC
  2. PyInit_sublist(void)
  3. {
  4. PyObject* m;
  5. SubListType.tp_base = &PyList_Type;
  6. if (PyType_Ready(&SubListType) < 0)
  7. return NULL;
  8. m = PyModule_Create(&sublistmodule);
  9. if (m == NULL)
  10. return NULL;
  11. Py_INCREF(&SubListType);
  12. if (PyModule_AddObject(m, "SubList", (PyObject *) &SubListType) < 0) {
  13. Py_DECREF(&SubListType);
  14. Py_DECREF(m);
  15. return NULL;
  16. }
  17. return m;
  18. }

Before calling PyType_Ready(), the type structure must have the tp_base slot filled in. When we are deriving an existing type, it is not necessary to fill out the tp_alloc slot with PyType_GenericNew() — the allocation function from the base type will be inherited.

After that, calling PyType_Ready() and adding the type object to the module is the same as with the basic Custom examples.

备注

1

This is true when we know that the object is a basic type, like a string or a float.

2

We relied on this in the tp_dealloc handler in this example, because our type doesn’t support garbage collection.

3

We now know that the first and last members are strings, so perhaps we could be less careful about decrementing their reference counts, however, we accept instances of string subclasses. Even though deallocating normal strings won’t call back into our objects, we can’t guarantee that deallocating an instance of a string subclass won’t call back into our objects.

4

Also, even with our attributes restricted to strings instances, the user could pass arbitrary str subclasses and therefore still create reference cycles.