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