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