Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1 | .. highlightlang:: c |
| 2 | |
| 3 | |
| 4 | .. _defining-new-types: |
| 5 | |
| 6 | ****************** |
| 7 | Defining New Types |
| 8 | ****************** |
| 9 | |
| 10 | .. sectionauthor:: Michael Hudson <mwh@python.net> |
| 11 | .. sectionauthor:: Dave Kuhlman <dkuhlman@rexx.com> |
| 12 | .. sectionauthor:: Jim Fulton <jim@zope.com> |
| 13 | |
| 14 | |
| 15 | As mentioned in the last chapter, Python allows the writer of an extension |
| 16 | module to define new types that can be manipulated from Python code, much like |
| 17 | strings and lists in core Python. |
| 18 | |
| 19 | This is not hard; the code for all extension types follows a pattern, but there |
| 20 | are some details that you need to understand before you can get started. |
| 21 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 22 | |
| 23 | .. _dnt-basics: |
| 24 | |
| 25 | The Basics |
| 26 | ========== |
| 27 | |
| 28 | The Python runtime sees all Python objects as variables of type |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 29 | :c:type:`PyObject\*`, which serves as a "base type" for all Python objects. |
| 30 | :c:type:`PyObject` itself only contains the refcount and a pointer to the |
| 31 | object's "type object". This is where the action is; the type object determines |
| 32 | which (C) functions get called when, for instance, an attribute gets looked |
| 33 | up on an object or it is multiplied by another object. These C functions |
| 34 | are called "type methods". |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 35 | |
| 36 | So, if you want to define a new object type, you need to create a new type |
| 37 | object. |
| 38 | |
| 39 | This sort of thing can only be explained by example, so here's a minimal, but |
| 40 | complete, module that defines a new type: |
| 41 | |
| 42 | .. literalinclude:: ../includes/noddy.c |
| 43 | |
| 44 | |
| 45 | Now that's quite a bit to take in at once, but hopefully bits will seem familiar |
| 46 | from the last chapter. |
| 47 | |
| 48 | The first bit that will be new is:: |
| 49 | |
| 50 | typedef struct { |
| 51 | PyObject_HEAD |
| 52 | } noddy_NoddyObject; |
| 53 | |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 54 | This is what a Noddy object will contain---in this case, nothing more than what |
| 55 | every Python object contains---a refcount and a pointer to a type object. |
| 56 | These are the fields the ``PyObject_HEAD`` macro brings in. The reason for the |
| 57 | macro is to standardize the layout and to enable special debugging fields in |
| 58 | debug builds. Note that there is no semicolon after the ``PyObject_HEAD`` |
| 59 | macro; one is included in the macro definition. Be wary of adding one by |
| 60 | accident; it's easy to do from habit, and your compiler might not complain, |
| 61 | but someone else's probably will! (On Windows, MSVC is known to call this an |
| 62 | error and refuse to compile the code.) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 63 | |
| 64 | For contrast, let's take a look at the corresponding definition for standard |
Georg Brandl | da65f60 | 2007-12-08 18:59:56 +0000 | [diff] [blame] | 65 | Python floats:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 66 | |
| 67 | typedef struct { |
| 68 | PyObject_HEAD |
Georg Brandl | da65f60 | 2007-12-08 18:59:56 +0000 | [diff] [blame] | 69 | double ob_fval; |
| 70 | } PyFloatObject; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 71 | |
| 72 | Moving on, we come to the crunch --- the type object. :: |
| 73 | |
| 74 | static PyTypeObject noddy_NoddyType = { |
Georg Brandl | ec12e82 | 2009-02-27 17:11:23 +0000 | [diff] [blame] | 75 | PyVarObject_HEAD_INIT(NULL, 0) |
Georg Brandl | 913b2a3 | 2008-12-05 15:12:15 +0000 | [diff] [blame] | 76 | "noddy.Noddy", /* tp_name */ |
| 77 | sizeof(noddy_NoddyObject), /* tp_basicsize */ |
| 78 | 0, /* tp_itemsize */ |
| 79 | 0, /* tp_dealloc */ |
| 80 | 0, /* tp_print */ |
| 81 | 0, /* tp_getattr */ |
| 82 | 0, /* tp_setattr */ |
Mark Dickinson | 9f98926 | 2009-02-02 21:29:40 +0000 | [diff] [blame] | 83 | 0, /* tp_reserved */ |
Georg Brandl | 913b2a3 | 2008-12-05 15:12:15 +0000 | [diff] [blame] | 84 | 0, /* tp_repr */ |
| 85 | 0, /* tp_as_number */ |
| 86 | 0, /* tp_as_sequence */ |
| 87 | 0, /* tp_as_mapping */ |
| 88 | 0, /* tp_hash */ |
| 89 | 0, /* tp_call */ |
| 90 | 0, /* tp_str */ |
| 91 | 0, /* tp_getattro */ |
| 92 | 0, /* tp_setattro */ |
| 93 | 0, /* tp_as_buffer */ |
| 94 | Py_TPFLAGS_DEFAULT, /* tp_flags */ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 95 | "Noddy objects", /* tp_doc */ |
| 96 | }; |
| 97 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 98 | Now if you go and look up the definition of :c:type:`PyTypeObject` in |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 99 | :file:`object.h` you'll see that it has many more fields that the definition |
| 100 | above. The remaining fields will be filled with zeros by the C compiler, and |
| 101 | it's common practice to not specify them explicitly unless you need them. |
| 102 | |
| 103 | This is so important that we're going to pick the top of it apart still |
| 104 | further:: |
| 105 | |
Georg Brandl | ec12e82 | 2009-02-27 17:11:23 +0000 | [diff] [blame] | 106 | PyVarObject_HEAD_INIT(NULL, 0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 107 | |
| 108 | This line is a bit of a wart; what we'd like to write is:: |
| 109 | |
Georg Brandl | ec12e82 | 2009-02-27 17:11:23 +0000 | [diff] [blame] | 110 | PyVarObject_HEAD_INIT(&PyType_Type, 0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 111 | |
| 112 | as the type of a type object is "type", but this isn't strictly conforming C and |
| 113 | some compilers complain. Fortunately, this member will be filled in for us by |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 114 | :c:func:`PyType_Ready`. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 115 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 116 | "noddy.Noddy", /* tp_name */ |
| 117 | |
| 118 | The name of our type. This will appear in the default textual representation of |
| 119 | our objects and in some error messages, for example:: |
| 120 | |
| 121 | >>> "" + noddy.new_noddy() |
| 122 | Traceback (most recent call last): |
| 123 | File "<stdin>", line 1, in ? |
| 124 | TypeError: cannot add type "noddy.Noddy" to string |
| 125 | |
| 126 | Note that the name is a dotted name that includes both the module name and the |
| 127 | name of the type within the module. The module in this case is :mod:`noddy` and |
| 128 | the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`. :: |
| 129 | |
| 130 | sizeof(noddy_NoddyObject), /* tp_basicsize */ |
| 131 | |
| 132 | This is so that Python knows how much memory to allocate when you call |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 133 | :c:func:`PyObject_New`. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 134 | |
| 135 | .. note:: |
| 136 | |
| 137 | If you want your type to be subclassable from Python, and your type has the same |
| 138 | :attr:`tp_basicsize` as its base type, you may have problems with multiple |
| 139 | inheritance. A Python subclass of your type will have to list your type first |
| 140 | in its :attr:`__bases__`, or else it will not be able to call your type's |
| 141 | :meth:`__new__` method without getting an error. You can avoid this problem by |
| 142 | ensuring that your type has a larger value for :attr:`tp_basicsize` than its |
| 143 | base type does. Most of the time, this will be true anyway, because either your |
| 144 | base type will be :class:`object`, or else you will be adding data members to |
| 145 | your base type, and therefore increasing its size. |
| 146 | |
| 147 | :: |
| 148 | |
| 149 | 0, /* tp_itemsize */ |
| 150 | |
| 151 | This has to do with variable length objects like lists and strings. Ignore this |
| 152 | for now. |
| 153 | |
| 154 | Skipping a number of type methods that we don't provide, we set the class flags |
| 155 | to :const:`Py_TPFLAGS_DEFAULT`. :: |
| 156 | |
Georg Brandl | 913b2a3 | 2008-12-05 15:12:15 +0000 | [diff] [blame] | 157 | Py_TPFLAGS_DEFAULT, /* tp_flags */ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 158 | |
| 159 | All types should include this constant in their flags. It enables all of the |
| 160 | members defined by the current version of Python. |
| 161 | |
| 162 | We provide a doc string for the type in :attr:`tp_doc`. :: |
| 163 | |
| 164 | "Noddy objects", /* tp_doc */ |
| 165 | |
| 166 | Now we get into the type methods, the things that make your objects different |
| 167 | from the others. We aren't going to implement any of these in this version of |
| 168 | the module. We'll expand this example later to have more interesting behavior. |
| 169 | |
| 170 | For now, all we want to be able to do is to create new :class:`Noddy` objects. |
| 171 | To enable object creation, we have to provide a :attr:`tp_new` implementation. |
| 172 | In this case, we can just use the default implementation provided by the API |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 173 | function :c:func:`PyType_GenericNew`. We'd like to just assign this to the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 174 | :attr:`tp_new` slot, but we can't, for portability sake, On some platforms or |
| 175 | compilers, we can't statically initialize a structure member with a function |
| 176 | defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot |
| 177 | in the module initialization function just before calling |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 178 | :c:func:`PyType_Ready`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 179 | |
| 180 | noddy_NoddyType.tp_new = PyType_GenericNew; |
| 181 | if (PyType_Ready(&noddy_NoddyType) < 0) |
| 182 | return; |
| 183 | |
| 184 | All the other type methods are *NULL*, so we'll go over them later --- that's |
| 185 | for a later section! |
| 186 | |
| 187 | Everything else in the file should be familiar, except for some code in |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 188 | :c:func:`PyInit_noddy`:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 189 | |
| 190 | if (PyType_Ready(&noddy_NoddyType) < 0) |
| 191 | return; |
| 192 | |
| 193 | This initializes the :class:`Noddy` type, filing in a number of members, |
| 194 | including :attr:`ob_type` that we initially set to *NULL*. :: |
| 195 | |
| 196 | PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType); |
| 197 | |
| 198 | This adds the type to the module dictionary. This allows us to create |
| 199 | :class:`Noddy` instances by calling the :class:`Noddy` class:: |
| 200 | |
| 201 | >>> import noddy |
| 202 | >>> mynoddy = noddy.Noddy() |
| 203 | |
| 204 | That's it! All that remains is to build it; put the above code in a file called |
| 205 | :file:`noddy.c` and :: |
| 206 | |
| 207 | from distutils.core import setup, Extension |
| 208 | setup(name="noddy", version="1.0", |
| 209 | ext_modules=[Extension("noddy", ["noddy.c"])]) |
| 210 | |
| 211 | in a file called :file:`setup.py`; then typing :: |
| 212 | |
| 213 | $ python setup.py build |
| 214 | |
| 215 | at a shell should produce a file :file:`noddy.so` in a subdirectory; move to |
| 216 | that directory and fire up Python --- you should be able to ``import noddy`` and |
| 217 | play around with Noddy objects. |
| 218 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 219 | That wasn't so hard, was it? |
| 220 | |
| 221 | Of course, the current Noddy type is pretty uninteresting. It has no data and |
| 222 | doesn't do anything. It can't even be subclassed. |
| 223 | |
| 224 | |
| 225 | Adding data and methods to the Basic example |
| 226 | -------------------------------------------- |
| 227 | |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 228 | Let's extend the basic example to add some data and methods. Let's also make |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 229 | the type usable as a base class. We'll create a new module, :mod:`noddy2` that |
| 230 | adds these capabilities: |
| 231 | |
| 232 | .. literalinclude:: ../includes/noddy2.c |
| 233 | |
| 234 | |
| 235 | This version of the module has a number of changes. |
| 236 | |
| 237 | We've added an extra include:: |
| 238 | |
Georg Brandl | 7bc6e4f | 2010-03-21 10:03:36 +0000 | [diff] [blame] | 239 | #include <structmember.h> |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 240 | |
| 241 | This include provides declarations that we use to handle attributes, as |
| 242 | described a bit later. |
| 243 | |
| 244 | The name of the :class:`Noddy` object structure has been shortened to |
| 245 | :class:`Noddy`. The type object name has been shortened to :class:`NoddyType`. |
| 246 | |
| 247 | The :class:`Noddy` type now has three data attributes, *first*, *last*, and |
| 248 | *number*. The *first* and *last* variables are Python strings containing first |
| 249 | and last names. The *number* attribute is an integer. |
| 250 | |
| 251 | The object structure is updated accordingly:: |
| 252 | |
| 253 | typedef struct { |
| 254 | PyObject_HEAD |
| 255 | PyObject *first; |
| 256 | PyObject *last; |
| 257 | int number; |
| 258 | } Noddy; |
| 259 | |
| 260 | Because we now have data to manage, we have to be more careful about object |
| 261 | allocation and deallocation. At a minimum, we need a deallocation method:: |
| 262 | |
| 263 | static void |
| 264 | Noddy_dealloc(Noddy* self) |
| 265 | { |
| 266 | Py_XDECREF(self->first); |
| 267 | Py_XDECREF(self->last); |
Georg Brandl | 2ed237b | 2008-12-07 14:09:20 +0000 | [diff] [blame] | 268 | Py_TYPE(self)->tp_free((PyObject*)self); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 269 | } |
| 270 | |
| 271 | which is assigned to the :attr:`tp_dealloc` member:: |
| 272 | |
| 273 | (destructor)Noddy_dealloc, /*tp_dealloc*/ |
| 274 | |
| 275 | This method decrements the reference counts of the two Python attributes. We use |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 276 | :c:func:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 277 | could be *NULL*. It then calls the :attr:`tp_free` member of the object's type |
| 278 | to free the object's memory. Note that the object's type might not be |
| 279 | :class:`NoddyType`, because the object may be an instance of a subclass. |
| 280 | |
| 281 | We want to make sure that the first and last names are initialized to empty |
| 282 | strings, so we provide a new method:: |
| 283 | |
| 284 | static PyObject * |
| 285 | Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds) |
| 286 | { |
| 287 | Noddy *self; |
| 288 | |
| 289 | self = (Noddy *)type->tp_alloc(type, 0); |
| 290 | if (self != NULL) { |
| 291 | self->first = PyString_FromString(""); |
Eli Bendersky | 47fe5c0 | 2011-08-12 11:40:39 +0300 | [diff] [blame] | 292 | if (self->first == NULL) { |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 293 | Py_DECREF(self); |
| 294 | return NULL; |
Eli Bendersky | 47fe5c0 | 2011-08-12 11:40:39 +0300 | [diff] [blame] | 295 | } |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 296 | |
| 297 | self->last = PyString_FromString(""); |
Eli Bendersky | 47fe5c0 | 2011-08-12 11:40:39 +0300 | [diff] [blame] | 298 | if (self->last == NULL) { |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 299 | Py_DECREF(self); |
| 300 | return NULL; |
Eli Bendersky | 47fe5c0 | 2011-08-12 11:40:39 +0300 | [diff] [blame] | 301 | } |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 302 | |
| 303 | self->number = 0; |
| 304 | } |
| 305 | |
| 306 | return (PyObject *)self; |
| 307 | } |
| 308 | |
| 309 | and install it in the :attr:`tp_new` member:: |
| 310 | |
| 311 | Noddy_new, /* tp_new */ |
| 312 | |
| 313 | The new member is responsible for creating (as opposed to initializing) objects |
| 314 | of the type. It is exposed in Python as the :meth:`__new__` method. See the |
| 315 | paper titled "Unifying types and classes in Python" for a detailed discussion of |
| 316 | the :meth:`__new__` method. One reason to implement a new method is to assure |
| 317 | the initial values of instance variables. In this case, we use the new method |
| 318 | to make sure that the initial values of the members :attr:`first` and |
| 319 | :attr:`last` are not *NULL*. If we didn't care whether the initial values were |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 320 | *NULL*, we could have used :c:func:`PyType_GenericNew` as our new method, as we |
| 321 | did before. :c:func:`PyType_GenericNew` initializes all of the instance variable |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 322 | members to *NULL*. |
| 323 | |
| 324 | The new method is a static method that is passed the type being instantiated and |
| 325 | any arguments passed when the type was called, and that returns the new object |
| 326 | created. New methods always accept positional and keyword arguments, but they |
| 327 | often ignore the arguments, leaving the argument handling to initializer |
| 328 | methods. Note that if the type supports subclassing, the type passed may not be |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 329 | the type being defined. The new method calls the :attr:`tp_alloc` slot to |
| 330 | allocate memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 331 | :c:func:`PyType_Ready` fills it for us by inheriting it from our base class, |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 332 | which is :class:`object` by default. Most types use the default allocation. |
| 333 | |
| 334 | .. note:: |
| 335 | |
| 336 | If you are creating a co-operative :attr:`tp_new` (one that calls a base type's |
| 337 | :attr:`tp_new` or :meth:`__new__`), you must *not* try to determine what method |
| 338 | to call using method resolution order at runtime. Always statically determine |
| 339 | what type you are going to call, and call its :attr:`tp_new` directly, or via |
| 340 | ``type->tp_base->tp_new``. If you do not do this, Python subclasses of your |
| 341 | type that also inherit from other Python-defined classes may not work correctly. |
| 342 | (Specifically, you may not be able to create instances of such subclasses |
| 343 | without getting a :exc:`TypeError`.) |
| 344 | |
| 345 | We provide an initialization function:: |
| 346 | |
| 347 | static int |
| 348 | Noddy_init(Noddy *self, PyObject *args, PyObject *kwds) |
| 349 | { |
| 350 | PyObject *first=NULL, *last=NULL, *tmp; |
| 351 | |
| 352 | static char *kwlist[] = {"first", "last", "number", NULL}; |
| 353 | |
| 354 | if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist, |
| 355 | &first, &last, |
| 356 | &self->number)) |
| 357 | return -1; |
| 358 | |
| 359 | if (first) { |
| 360 | tmp = self->first; |
| 361 | Py_INCREF(first); |
| 362 | self->first = first; |
| 363 | Py_XDECREF(tmp); |
| 364 | } |
| 365 | |
| 366 | if (last) { |
| 367 | tmp = self->last; |
| 368 | Py_INCREF(last); |
| 369 | self->last = last; |
| 370 | Py_XDECREF(tmp); |
| 371 | } |
| 372 | |
| 373 | return 0; |
| 374 | } |
| 375 | |
| 376 | by filling the :attr:`tp_init` slot. :: |
| 377 | |
| 378 | (initproc)Noddy_init, /* tp_init */ |
| 379 | |
| 380 | The :attr:`tp_init` slot is exposed in Python as the :meth:`__init__` method. It |
| 381 | is used to initialize an object after it's created. Unlike the new method, we |
| 382 | can't guarantee that the initializer is called. The initializer isn't called |
| 383 | when unpickling objects and it can be overridden. Our initializer accepts |
| 384 | arguments to provide initial values for our instance. Initializers always accept |
| 385 | positional and keyword arguments. |
| 386 | |
| 387 | Initializers can be called multiple times. Anyone can call the :meth:`__init__` |
| 388 | method on our objects. For this reason, we have to be extra careful when |
| 389 | assigning the new values. We might be tempted, for example to assign the |
| 390 | :attr:`first` member like this:: |
| 391 | |
| 392 | if (first) { |
| 393 | Py_XDECREF(self->first); |
| 394 | Py_INCREF(first); |
| 395 | self->first = first; |
| 396 | } |
| 397 | |
| 398 | But this would be risky. Our type doesn't restrict the type of the |
| 399 | :attr:`first` member, so it could be any kind of object. It could have a |
| 400 | destructor that causes code to be executed that tries to access the |
| 401 | :attr:`first` member. To be paranoid and protect ourselves against this |
| 402 | possibility, we almost always reassign members before decrementing their |
| 403 | reference counts. When don't we have to do this? |
| 404 | |
| 405 | * when we absolutely know that the reference count is greater than 1 |
| 406 | |
| 407 | * when we know that deallocation of the object [#]_ will not cause any calls |
| 408 | back into our type's code |
| 409 | |
| 410 | * when decrementing a reference count in a :attr:`tp_dealloc` handler when |
| 411 | garbage-collections is not supported [#]_ |
| 412 | |
Christian Heimes | f75b290 | 2008-03-16 17:29:44 +0000 | [diff] [blame] | 413 | We want to expose our instance variables as attributes. There are a |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 414 | number of ways to do that. The simplest way is to define member definitions:: |
| 415 | |
| 416 | static PyMemberDef Noddy_members[] = { |
| 417 | {"first", T_OBJECT_EX, offsetof(Noddy, first), 0, |
| 418 | "first name"}, |
| 419 | {"last", T_OBJECT_EX, offsetof(Noddy, last), 0, |
| 420 | "last name"}, |
| 421 | {"number", T_INT, offsetof(Noddy, number), 0, |
| 422 | "noddy number"}, |
| 423 | {NULL} /* Sentinel */ |
| 424 | }; |
| 425 | |
| 426 | and put the definitions in the :attr:`tp_members` slot:: |
| 427 | |
| 428 | Noddy_members, /* tp_members */ |
| 429 | |
| 430 | Each member definition has a member name, type, offset, access flags and |
R. David Murray | bcb8d3a | 2010-06-01 01:11:18 +0000 | [diff] [blame] | 431 | documentation string. See the :ref:`Generic-Attribute-Management` section below for |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 432 | details. |
| 433 | |
| 434 | A disadvantage of this approach is that it doesn't provide a way to restrict the |
| 435 | types of objects that can be assigned to the Python attributes. We expect the |
| 436 | first and last names to be strings, but any Python objects can be assigned. |
| 437 | Further, the attributes can be deleted, setting the C pointers to *NULL*. Even |
| 438 | though we can make sure the members are initialized to non-*NULL* values, the |
| 439 | members can be set to *NULL* if the attributes are deleted. |
| 440 | |
| 441 | We define a single method, :meth:`name`, that outputs the objects name as the |
| 442 | concatenation of the first and last names. :: |
| 443 | |
| 444 | static PyObject * |
| 445 | Noddy_name(Noddy* self) |
| 446 | { |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 447 | if (self->first == NULL) { |
| 448 | PyErr_SetString(PyExc_AttributeError, "first"); |
| 449 | return NULL; |
| 450 | } |
| 451 | |
| 452 | if (self->last == NULL) { |
| 453 | PyErr_SetString(PyExc_AttributeError, "last"); |
| 454 | return NULL; |
| 455 | } |
| 456 | |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 457 | return PyUnicode_FromFormat("%S %S", self->first, self->last); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 458 | } |
| 459 | |
| 460 | The method is implemented as a C function that takes a :class:`Noddy` (or |
| 461 | :class:`Noddy` subclass) instance as the first argument. Methods always take an |
| 462 | instance as the first argument. Methods often take positional and keyword |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 463 | arguments as well, but in this case we don't take any and don't need to accept |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 464 | a positional argument tuple or keyword argument dictionary. This method is |
| 465 | equivalent to the Python method:: |
| 466 | |
| 467 | def name(self): |
| 468 | return "%s %s" % (self.first, self.last) |
| 469 | |
| 470 | Note that we have to check for the possibility that our :attr:`first` and |
| 471 | :attr:`last` members are *NULL*. This is because they can be deleted, in which |
| 472 | case they are set to *NULL*. It would be better to prevent deletion of these |
| 473 | attributes and to restrict the attribute values to be strings. We'll see how to |
| 474 | do that in the next section. |
| 475 | |
| 476 | Now that we've defined the method, we need to create an array of method |
| 477 | definitions:: |
| 478 | |
| 479 | static PyMethodDef Noddy_methods[] = { |
| 480 | {"name", (PyCFunction)Noddy_name, METH_NOARGS, |
| 481 | "Return the name, combining the first and last name" |
| 482 | }, |
| 483 | {NULL} /* Sentinel */ |
| 484 | }; |
| 485 | |
| 486 | and assign them to the :attr:`tp_methods` slot:: |
| 487 | |
| 488 | Noddy_methods, /* tp_methods */ |
| 489 | |
| 490 | Note that we used the :const:`METH_NOARGS` flag to indicate that the method is |
| 491 | passed no arguments. |
| 492 | |
| 493 | Finally, we'll make our type usable as a base class. We've written our methods |
| 494 | carefully so far so that they don't make any assumptions about the type of the |
| 495 | object being created or used, so all we need to do is to add the |
| 496 | :const:`Py_TPFLAGS_BASETYPE` to our class flag definition:: |
| 497 | |
| 498 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/ |
| 499 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 500 | We rename :c:func:`PyInit_noddy` to :c:func:`PyInit_noddy2` and update the module |
| 501 | name in the :c:type:`PyModuleDef` struct. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 502 | |
| 503 | Finally, we update our :file:`setup.py` file to build the new module:: |
| 504 | |
| 505 | from distutils.core import setup, Extension |
| 506 | setup(name="noddy", version="1.0", |
| 507 | ext_modules=[ |
| 508 | Extension("noddy", ["noddy.c"]), |
| 509 | Extension("noddy2", ["noddy2.c"]), |
| 510 | ]) |
| 511 | |
| 512 | |
| 513 | Providing finer control over data attributes |
| 514 | -------------------------------------------- |
| 515 | |
| 516 | In this section, we'll provide finer control over how the :attr:`first` and |
| 517 | :attr:`last` attributes are set in the :class:`Noddy` example. In the previous |
| 518 | version of our module, the instance variables :attr:`first` and :attr:`last` |
| 519 | could be set to non-string values or even deleted. We want to make sure that |
| 520 | these attributes always contain strings. |
| 521 | |
| 522 | .. literalinclude:: ../includes/noddy3.c |
| 523 | |
| 524 | |
| 525 | To provide greater control, over the :attr:`first` and :attr:`last` attributes, |
| 526 | we'll use custom getter and setter functions. Here are the functions for |
| 527 | getting and setting the :attr:`first` attribute:: |
| 528 | |
| 529 | Noddy_getfirst(Noddy *self, void *closure) |
| 530 | { |
| 531 | Py_INCREF(self->first); |
| 532 | return self->first; |
| 533 | } |
| 534 | |
| 535 | static int |
| 536 | Noddy_setfirst(Noddy *self, PyObject *value, void *closure) |
| 537 | { |
| 538 | if (value == NULL) { |
| 539 | PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute"); |
| 540 | return -1; |
| 541 | } |
| 542 | |
| 543 | if (! PyString_Check(value)) { |
| 544 | PyErr_SetString(PyExc_TypeError, |
| 545 | "The first attribute value must be a string"); |
| 546 | return -1; |
| 547 | } |
| 548 | |
| 549 | Py_DECREF(self->first); |
| 550 | Py_INCREF(value); |
| 551 | self->first = value; |
| 552 | |
| 553 | return 0; |
| 554 | } |
| 555 | |
| 556 | The getter function is passed a :class:`Noddy` object and a "closure", which is |
| 557 | void pointer. In this case, the closure is ignored. (The closure supports an |
| 558 | advanced usage in which definition data is passed to the getter and setter. This |
| 559 | could, for example, be used to allow a single set of getter and setter functions |
| 560 | that decide the attribute to get or set based on data in the closure.) |
| 561 | |
| 562 | The setter function is passed the :class:`Noddy` object, the new value, and the |
| 563 | closure. The new value may be *NULL*, in which case the attribute is being |
| 564 | deleted. In our setter, we raise an error if the attribute is deleted or if the |
| 565 | attribute value is not a string. |
| 566 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 567 | We create an array of :c:type:`PyGetSetDef` structures:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 568 | |
| 569 | static PyGetSetDef Noddy_getseters[] = { |
| 570 | {"first", |
| 571 | (getter)Noddy_getfirst, (setter)Noddy_setfirst, |
| 572 | "first name", |
| 573 | NULL}, |
| 574 | {"last", |
| 575 | (getter)Noddy_getlast, (setter)Noddy_setlast, |
| 576 | "last name", |
| 577 | NULL}, |
| 578 | {NULL} /* Sentinel */ |
| 579 | }; |
| 580 | |
| 581 | and register it in the :attr:`tp_getset` slot:: |
| 582 | |
| 583 | Noddy_getseters, /* tp_getset */ |
| 584 | |
Christian Heimes | f75b290 | 2008-03-16 17:29:44 +0000 | [diff] [blame] | 585 | to register our attribute getters and setters. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 586 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 587 | The last item in a :c:type:`PyGetSetDef` structure is the closure mentioned |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 588 | above. In this case, we aren't using the closure, so we just pass *NULL*. |
| 589 | |
| 590 | We also remove the member definitions for these attributes:: |
| 591 | |
| 592 | static PyMemberDef Noddy_members[] = { |
| 593 | {"number", T_INT, offsetof(Noddy, number), 0, |
| 594 | "noddy number"}, |
| 595 | {NULL} /* Sentinel */ |
| 596 | }; |
| 597 | |
| 598 | We also need to update the :attr:`tp_init` handler to only allow strings [#]_ to |
| 599 | be passed:: |
| 600 | |
| 601 | static int |
| 602 | Noddy_init(Noddy *self, PyObject *args, PyObject *kwds) |
| 603 | { |
| 604 | PyObject *first=NULL, *last=NULL, *tmp; |
| 605 | |
| 606 | static char *kwlist[] = {"first", "last", "number", NULL}; |
| 607 | |
| 608 | if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SSi", kwlist, |
| 609 | &first, &last, |
| 610 | &self->number)) |
| 611 | return -1; |
| 612 | |
| 613 | if (first) { |
| 614 | tmp = self->first; |
| 615 | Py_INCREF(first); |
| 616 | self->first = first; |
| 617 | Py_DECREF(tmp); |
| 618 | } |
| 619 | |
| 620 | if (last) { |
| 621 | tmp = self->last; |
| 622 | Py_INCREF(last); |
| 623 | self->last = last; |
| 624 | Py_DECREF(tmp); |
| 625 | } |
| 626 | |
| 627 | return 0; |
| 628 | } |
| 629 | |
| 630 | With these changes, we can assure that the :attr:`first` and :attr:`last` |
| 631 | members are never *NULL* so we can remove checks for *NULL* values in almost all |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 632 | cases. This means that most of the :c:func:`Py_XDECREF` calls can be converted to |
| 633 | :c:func:`Py_DECREF` calls. The only place we can't change these calls is in the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 634 | deallocator, where there is the possibility that the initialization of these |
| 635 | members failed in the constructor. |
| 636 | |
| 637 | We also rename the module initialization function and module name in the |
| 638 | initialization function, as we did before, and we add an extra definition to the |
| 639 | :file:`setup.py` file. |
| 640 | |
| 641 | |
| 642 | Supporting cyclic garbage collection |
| 643 | ------------------------------------ |
| 644 | |
| 645 | Python has a cyclic-garbage collector that can identify unneeded objects even |
| 646 | when their reference counts are not zero. This can happen when objects are |
| 647 | involved in cycles. For example, consider:: |
| 648 | |
| 649 | >>> l = [] |
| 650 | >>> l.append(l) |
| 651 | >>> del l |
| 652 | |
| 653 | In this example, we create a list that contains itself. When we delete it, it |
| 654 | still has a reference from itself. Its reference count doesn't drop to zero. |
| 655 | Fortunately, Python's cyclic-garbage collector will eventually figure out that |
| 656 | the list is garbage and free it. |
| 657 | |
| 658 | In the second version of the :class:`Noddy` example, we allowed any kind of |
| 659 | object to be stored in the :attr:`first` or :attr:`last` attributes. [#]_ This |
| 660 | means that :class:`Noddy` objects can participate in cycles:: |
| 661 | |
| 662 | >>> import noddy2 |
| 663 | >>> n = noddy2.Noddy() |
| 664 | >>> l = [n] |
| 665 | >>> n.first = l |
| 666 | |
| 667 | This is pretty silly, but it gives us an excuse to add support for the |
| 668 | cyclic-garbage collector to the :class:`Noddy` example. To support cyclic |
| 669 | garbage collection, types need to fill two slots and set a class flag that |
| 670 | enables these slots: |
| 671 | |
| 672 | .. literalinclude:: ../includes/noddy4.c |
| 673 | |
| 674 | |
| 675 | The traversal method provides access to subobjects that could participate in |
| 676 | cycles:: |
| 677 | |
| 678 | static int |
| 679 | Noddy_traverse(Noddy *self, visitproc visit, void *arg) |
| 680 | { |
| 681 | int vret; |
| 682 | |
| 683 | if (self->first) { |
| 684 | vret = visit(self->first, arg); |
| 685 | if (vret != 0) |
| 686 | return vret; |
| 687 | } |
| 688 | if (self->last) { |
| 689 | vret = visit(self->last, arg); |
| 690 | if (vret != 0) |
| 691 | return vret; |
| 692 | } |
| 693 | |
| 694 | return 0; |
| 695 | } |
| 696 | |
| 697 | For each subobject that can participate in cycles, we need to call the |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 698 | :c:func:`visit` function, which is passed to the traversal method. The |
| 699 | :c:func:`visit` function takes as arguments the subobject and the extra argument |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 700 | *arg* passed to the traversal method. It returns an integer value that must be |
| 701 | returned if it is non-zero. |
| 702 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 703 | Python provides a :c:func:`Py_VISIT` macro that automates calling visit |
| 704 | functions. With :c:func:`Py_VISIT`, :c:func:`Noddy_traverse` can be simplified:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 705 | |
| 706 | static int |
| 707 | Noddy_traverse(Noddy *self, visitproc visit, void *arg) |
| 708 | { |
| 709 | Py_VISIT(self->first); |
| 710 | Py_VISIT(self->last); |
| 711 | return 0; |
| 712 | } |
| 713 | |
| 714 | .. note:: |
| 715 | |
| 716 | Note that the :attr:`tp_traverse` implementation must name its arguments exactly |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 717 | *visit* and *arg* in order to use :c:func:`Py_VISIT`. This is to encourage |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 718 | uniformity across these boring implementations. |
| 719 | |
| 720 | We also need to provide a method for clearing any subobjects that can |
| 721 | participate in cycles. We implement the method and reimplement the deallocator |
| 722 | to use it:: |
| 723 | |
| 724 | static int |
| 725 | Noddy_clear(Noddy *self) |
| 726 | { |
| 727 | PyObject *tmp; |
| 728 | |
| 729 | tmp = self->first; |
| 730 | self->first = NULL; |
| 731 | Py_XDECREF(tmp); |
| 732 | |
| 733 | tmp = self->last; |
| 734 | self->last = NULL; |
| 735 | Py_XDECREF(tmp); |
| 736 | |
| 737 | return 0; |
| 738 | } |
| 739 | |
| 740 | static void |
| 741 | Noddy_dealloc(Noddy* self) |
| 742 | { |
| 743 | Noddy_clear(self); |
Georg Brandl | 2ed237b | 2008-12-07 14:09:20 +0000 | [diff] [blame] | 744 | Py_TYPE(self)->tp_free((PyObject*)self); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 745 | } |
| 746 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 747 | Notice the use of a temporary variable in :c:func:`Noddy_clear`. We use the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 748 | temporary variable so that we can set each member to *NULL* before decrementing |
| 749 | its reference count. We do this because, as was discussed earlier, if the |
| 750 | reference count drops to zero, we might cause code to run that calls back into |
| 751 | the object. In addition, because we now support garbage collection, we also |
| 752 | have to worry about code being run that triggers garbage collection. If garbage |
| 753 | collection is run, our :attr:`tp_traverse` handler could get called. We can't |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 754 | take a chance of having :c:func:`Noddy_traverse` called when a member's reference |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 755 | count has dropped to zero and its value hasn't been set to *NULL*. |
| 756 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 757 | Python provides a :c:func:`Py_CLEAR` that automates the careful decrementing of |
| 758 | reference counts. With :c:func:`Py_CLEAR`, the :c:func:`Noddy_clear` function can |
Georg Brandl | e6bcc91 | 2008-05-12 18:05:20 +0000 | [diff] [blame] | 759 | be simplified:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 760 | |
| 761 | static int |
| 762 | Noddy_clear(Noddy *self) |
| 763 | { |
| 764 | Py_CLEAR(self->first); |
| 765 | Py_CLEAR(self->last); |
| 766 | return 0; |
| 767 | } |
| 768 | |
| 769 | Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags:: |
| 770 | |
Georg Brandl | 913b2a3 | 2008-12-05 15:12:15 +0000 | [diff] [blame] | 771 | Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* tp_flags */ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 772 | |
| 773 | That's pretty much it. If we had written custom :attr:`tp_alloc` or |
| 774 | :attr:`tp_free` slots, we'd need to modify them for cyclic-garbage collection. |
| 775 | Most extensions will use the versions automatically provided. |
| 776 | |
| 777 | |
| 778 | Subclassing other types |
| 779 | ----------------------- |
| 780 | |
| 781 | It is possible to create new extension types that are derived from existing |
| 782 | types. It is easiest to inherit from the built in types, since an extension can |
| 783 | easily use the :class:`PyTypeObject` it needs. It can be difficult to share |
| 784 | these :class:`PyTypeObject` structures between extension modules. |
| 785 | |
| 786 | In this example we will create a :class:`Shoddy` type that inherits from the |
Georg Brandl | 22b3431 | 2009-07-26 14:54:51 +0000 | [diff] [blame] | 787 | built-in :class:`list` type. The new type will be completely compatible with |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 788 | regular lists, but will have an additional :meth:`increment` method that |
| 789 | increases an internal counter. :: |
| 790 | |
| 791 | >>> import shoddy |
| 792 | >>> s = shoddy.Shoddy(range(3)) |
| 793 | >>> s.extend(s) |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 794 | >>> print(len(s)) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 795 | 6 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 796 | >>> print(s.increment()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 797 | 1 |
Georg Brandl | 6911e3c | 2007-09-04 07:15:32 +0000 | [diff] [blame] | 798 | >>> print(s.increment()) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 799 | 2 |
| 800 | |
| 801 | .. literalinclude:: ../includes/shoddy.c |
| 802 | |
| 803 | |
| 804 | As you can see, the source code closely resembles the :class:`Noddy` examples in |
| 805 | previous sections. We will break down the main differences between them. :: |
| 806 | |
| 807 | typedef struct { |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 808 | PyListObject list; |
| 809 | int state; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 810 | } Shoddy; |
| 811 | |
| 812 | The primary difference for derived type objects is that the base type's object |
| 813 | structure must be the first value. The base type will already include the |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 814 | :c:func:`PyObject_HEAD` at the beginning of its structure. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 815 | |
| 816 | When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can |
| 817 | be safely cast to both *PyListObject\** and *Shoddy\**. :: |
| 818 | |
| 819 | static int |
| 820 | Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds) |
| 821 | { |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 822 | if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0) |
| 823 | return -1; |
| 824 | self->state = 0; |
| 825 | return 0; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 826 | } |
| 827 | |
| 828 | In the :attr:`__init__` method for our type, we can see how to call through to |
| 829 | the :attr:`__init__` method of the base type. |
| 830 | |
| 831 | This pattern is important when writing a type with custom :attr:`new` and |
| 832 | :attr:`dealloc` methods. The :attr:`new` method should not actually create the |
| 833 | memory for the object with :attr:`tp_alloc`, that will be handled by the base |
| 834 | class when calling its :attr:`tp_new`. |
| 835 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 836 | When filling out the :c:func:`PyTypeObject` for the :class:`Shoddy` type, you see |
| 837 | a slot for :c:func:`tp_base`. Due to cross platform compiler issues, you can't |
| 838 | fill that field directly with the :c:func:`PyList_Type`; it can be done later in |
| 839 | the module's :c:func:`init` function. :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 840 | |
| 841 | PyMODINIT_FUNC |
Georg Brandl | 913b2a3 | 2008-12-05 15:12:15 +0000 | [diff] [blame] | 842 | PyInit_shoddy(void) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 843 | { |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 844 | PyObject *m; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 845 | |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 846 | ShoddyType.tp_base = &PyList_Type; |
| 847 | if (PyType_Ready(&ShoddyType) < 0) |
| 848 | return NULL; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 849 | |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 850 | m = PyModule_Create(&shoddymodule); |
| 851 | if (m == NULL) |
| 852 | return NULL; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 853 | |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 854 | Py_INCREF(&ShoddyType); |
| 855 | PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType); |
Georg Brandl | 2115176 | 2009-03-31 15:52:41 +0000 | [diff] [blame] | 856 | return m; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 857 | } |
| 858 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 859 | Before calling :c:func:`PyType_Ready`, the type structure must have the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 860 | :attr:`tp_base` slot filled in. When we are deriving a new type, it is not |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 861 | necessary to fill out the :attr:`tp_alloc` slot with :c:func:`PyType_GenericNew` |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 862 | -- the allocate function from the base type will be inherited. |
| 863 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 864 | After that, calling :c:func:`PyType_Ready` and adding the type object to the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 865 | module is the same as with the basic :class:`Noddy` examples. |
| 866 | |
| 867 | |
| 868 | .. _dnt-type-methods: |
| 869 | |
| 870 | Type Methods |
| 871 | ============ |
| 872 | |
| 873 | This section aims to give a quick fly-by on the various type methods you can |
| 874 | implement and what they do. |
| 875 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 876 | Here is the definition of :c:type:`PyTypeObject`, with some fields only used in |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 877 | debug builds omitted: |
| 878 | |
| 879 | .. literalinclude:: ../includes/typestruct.h |
| 880 | |
| 881 | |
| 882 | Now that's a *lot* of methods. Don't worry too much though - if you have a type |
| 883 | you want to define, the chances are very good that you will only implement a |
| 884 | handful of these. |
| 885 | |
| 886 | As you probably expect by now, we're going to go over this and give more |
| 887 | information about the various handlers. We won't go in the order they are |
| 888 | defined in the structure, because there is a lot of historical baggage that |
| 889 | impacts the ordering of the fields; be sure your type initialization keeps the |
| 890 | fields in the right order! It's often easiest to find an example that includes |
| 891 | all the fields you need (even if they're initialized to ``0``) and then change |
| 892 | the values to suit your new type. :: |
| 893 | |
| 894 | char *tp_name; /* For printing */ |
| 895 | |
| 896 | The name of the type - as mentioned in the last section, this will appear in |
| 897 | various places, almost entirely for diagnostic purposes. Try to choose something |
| 898 | that will be helpful in such a situation! :: |
| 899 | |
| 900 | int tp_basicsize, tp_itemsize; /* For allocation */ |
| 901 | |
| 902 | These fields tell the runtime how much memory to allocate when new objects of |
| 903 | this type are created. Python has some built-in support for variable length |
| 904 | structures (think: strings, lists) which is where the :attr:`tp_itemsize` field |
| 905 | comes in. This will be dealt with later. :: |
| 906 | |
| 907 | char *tp_doc; |
| 908 | |
| 909 | Here you can put a string (or its address) that you want returned when the |
| 910 | Python script references ``obj.__doc__`` to retrieve the doc string. |
| 911 | |
| 912 | Now we come to the basic type methods---the ones most extension types will |
| 913 | implement. |
| 914 | |
| 915 | |
| 916 | Finalization and De-allocation |
| 917 | ------------------------------ |
| 918 | |
| 919 | .. index:: |
| 920 | single: object; deallocation |
| 921 | single: deallocation, object |
| 922 | single: object; finalization |
| 923 | single: finalization, of objects |
| 924 | |
| 925 | :: |
| 926 | |
| 927 | destructor tp_dealloc; |
| 928 | |
| 929 | This function is called when the reference count of the instance of your type is |
| 930 | reduced to zero and the Python interpreter wants to reclaim it. If your type |
| 931 | has memory to free or other clean-up to perform, put it here. The object itself |
| 932 | needs to be freed here as well. Here is an example of this function:: |
| 933 | |
| 934 | static void |
| 935 | newdatatype_dealloc(newdatatypeobject * obj) |
| 936 | { |
| 937 | free(obj->obj_UnderlyingDatatypePtr); |
Georg Brandl | 2ed237b | 2008-12-07 14:09:20 +0000 | [diff] [blame] | 938 | Py_TYPE(obj)->tp_free(obj); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 939 | } |
| 940 | |
| 941 | .. index:: |
| 942 | single: PyErr_Fetch() |
| 943 | single: PyErr_Restore() |
| 944 | |
| 945 | One important requirement of the deallocator function is that it leaves any |
| 946 | pending exceptions alone. This is important since deallocators are frequently |
| 947 | called as the interpreter unwinds the Python stack; when the stack is unwound |
| 948 | due to an exception (rather than normal returns), nothing is done to protect the |
| 949 | deallocators from seeing that an exception has already been set. Any actions |
| 950 | which a deallocator performs which may cause additional Python code to be |
| 951 | executed may detect that an exception has been set. This can lead to misleading |
| 952 | errors from the interpreter. The proper way to protect against this is to save |
| 953 | a pending exception before performing the unsafe action, and restoring it when |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 954 | done. This can be done using the :c:func:`PyErr_Fetch` and |
| 955 | :c:func:`PyErr_Restore` functions:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 956 | |
| 957 | static void |
| 958 | my_dealloc(PyObject *obj) |
| 959 | { |
| 960 | MyObject *self = (MyObject *) obj; |
| 961 | PyObject *cbresult; |
| 962 | |
| 963 | if (self->my_callback != NULL) { |
| 964 | PyObject *err_type, *err_value, *err_traceback; |
| 965 | int have_error = PyErr_Occurred() ? 1 : 0; |
| 966 | |
| 967 | if (have_error) |
| 968 | PyErr_Fetch(&err_type, &err_value, &err_traceback); |
| 969 | |
| 970 | cbresult = PyObject_CallObject(self->my_callback, NULL); |
| 971 | if (cbresult == NULL) |
| 972 | PyErr_WriteUnraisable(self->my_callback); |
| 973 | else |
| 974 | Py_DECREF(cbresult); |
| 975 | |
| 976 | if (have_error) |
| 977 | PyErr_Restore(err_type, err_value, err_traceback); |
| 978 | |
| 979 | Py_DECREF(self->my_callback); |
| 980 | } |
Georg Brandl | 2ed237b | 2008-12-07 14:09:20 +0000 | [diff] [blame] | 981 | Py_TYPE(obj)->tp_free((PyObject*)self); |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 982 | } |
| 983 | |
| 984 | |
| 985 | Object Presentation |
| 986 | ------------------- |
| 987 | |
| 988 | .. index:: |
| 989 | builtin: repr |
| 990 | builtin: str |
| 991 | |
| 992 | In Python, there are two ways to generate a textual representation of an object: |
| 993 | the :func:`repr` function, and the :func:`str` function. (The :func:`print` |
| 994 | function just calls :func:`str`.) These handlers are both optional. |
| 995 | |
| 996 | :: |
| 997 | |
| 998 | reprfunc tp_repr; |
| 999 | reprfunc tp_str; |
| 1000 | |
| 1001 | The :attr:`tp_repr` handler should return a string object containing a |
| 1002 | representation of the instance for which it is called. Here is a simple |
| 1003 | example:: |
| 1004 | |
| 1005 | static PyObject * |
| 1006 | newdatatype_repr(newdatatypeobject * obj) |
| 1007 | { |
| 1008 | return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}", |
| 1009 | obj->obj_UnderlyingDatatypePtr->size); |
| 1010 | } |
| 1011 | |
| 1012 | If no :attr:`tp_repr` handler is specified, the interpreter will supply a |
| 1013 | representation that uses the type's :attr:`tp_name` and a uniquely-identifying |
| 1014 | value for the object. |
| 1015 | |
| 1016 | The :attr:`tp_str` handler is to :func:`str` what the :attr:`tp_repr` handler |
| 1017 | described above is to :func:`repr`; that is, it is called when Python code calls |
| 1018 | :func:`str` on an instance of your object. Its implementation is very similar |
| 1019 | to the :attr:`tp_repr` function, but the resulting string is intended for human |
| 1020 | consumption. If :attr:`tp_str` is not specified, the :attr:`tp_repr` handler is |
| 1021 | used instead. |
| 1022 | |
| 1023 | Here is a simple example:: |
| 1024 | |
| 1025 | static PyObject * |
| 1026 | newdatatype_str(newdatatypeobject * obj) |
| 1027 | { |
| 1028 | return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}", |
| 1029 | obj->obj_UnderlyingDatatypePtr->size); |
| 1030 | } |
| 1031 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1032 | |
| 1033 | |
| 1034 | Attribute Management |
| 1035 | -------------------- |
| 1036 | |
| 1037 | For every object which can support attributes, the corresponding type must |
| 1038 | provide the functions that control how the attributes are resolved. There needs |
| 1039 | to be a function which can retrieve attributes (if any are defined), and another |
| 1040 | to set attributes (if setting attributes is allowed). Removing an attribute is |
| 1041 | a special case, for which the new value passed to the handler is *NULL*. |
| 1042 | |
| 1043 | Python supports two pairs of attribute handlers; a type that supports attributes |
| 1044 | only needs to implement the functions for one pair. The difference is that one |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1045 | pair takes the name of the attribute as a :c:type:`char\*`, while the other |
| 1046 | accepts a :c:type:`PyObject\*`. Each type can use whichever pair makes more |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1047 | sense for the implementation's convenience. :: |
| 1048 | |
| 1049 | getattrfunc tp_getattr; /* char * version */ |
| 1050 | setattrfunc tp_setattr; |
| 1051 | /* ... */ |
Amaury Forgeot d'Arc | 87ce6d7 | 2008-07-02 22:59:48 +0000 | [diff] [blame] | 1052 | getattrofunc tp_getattro; /* PyObject * version */ |
| 1053 | setattrofunc tp_setattro; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1054 | |
| 1055 | If accessing attributes of an object is always a simple operation (this will be |
| 1056 | explained shortly), there are generic implementations which can be used to |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1057 | provide the :c:type:`PyObject\*` version of the attribute management functions. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1058 | The actual need for type-specific attribute handlers almost completely |
| 1059 | disappeared starting with Python 2.2, though there are many examples which have |
| 1060 | not been updated to use some of the new generic mechanism that is available. |
| 1061 | |
| 1062 | |
R. David Murray | bcb8d3a | 2010-06-01 01:11:18 +0000 | [diff] [blame] | 1063 | .. _generic-attribute-management: |
| 1064 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1065 | Generic Attribute Management |
| 1066 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1067 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1068 | Most extension types only use *simple* attributes. So, what makes the |
| 1069 | attributes simple? There are only a couple of conditions that must be met: |
| 1070 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1071 | #. The name of the attributes must be known when :c:func:`PyType_Ready` is |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1072 | called. |
| 1073 | |
| 1074 | #. No special processing is needed to record that an attribute was looked up or |
| 1075 | set, nor do actions need to be taken based on the value. |
| 1076 | |
| 1077 | Note that this list does not place any restrictions on the values of the |
| 1078 | attributes, when the values are computed, or how relevant data is stored. |
| 1079 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1080 | When :c:func:`PyType_Ready` is called, it uses three tables referenced by the |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1081 | type object to create :term:`descriptor`\s which are placed in the dictionary of the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1082 | type object. Each descriptor controls access to one attribute of the instance |
| 1083 | object. Each of the tables is optional; if all three are *NULL*, instances of |
| 1084 | the type will only have attributes that are inherited from their base type, and |
| 1085 | should leave the :attr:`tp_getattro` and :attr:`tp_setattro` fields *NULL* as |
| 1086 | well, allowing the base type to handle attributes. |
| 1087 | |
| 1088 | The tables are declared as three fields of the type object:: |
| 1089 | |
| 1090 | struct PyMethodDef *tp_methods; |
| 1091 | struct PyMemberDef *tp_members; |
| 1092 | struct PyGetSetDef *tp_getset; |
| 1093 | |
| 1094 | If :attr:`tp_methods` is not *NULL*, it must refer to an array of |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1095 | :c:type:`PyMethodDef` structures. Each entry in the table is an instance of this |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1096 | structure:: |
| 1097 | |
| 1098 | typedef struct PyMethodDef { |
| 1099 | char *ml_name; /* method name */ |
| 1100 | PyCFunction ml_meth; /* implementation function */ |
Georg Brandl | a1c6a1c | 2009-01-03 21:26:05 +0000 | [diff] [blame] | 1101 | int ml_flags; /* flags */ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1102 | char *ml_doc; /* docstring */ |
| 1103 | } PyMethodDef; |
| 1104 | |
| 1105 | One entry should be defined for each method provided by the type; no entries are |
| 1106 | needed for methods inherited from a base type. One additional entry is needed |
| 1107 | at the end; it is a sentinel that marks the end of the array. The |
| 1108 | :attr:`ml_name` field of the sentinel must be *NULL*. |
| 1109 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1110 | The second table is used to define attributes which map directly to data stored |
| 1111 | in the instance. A variety of primitive C types are supported, and access may |
| 1112 | be read-only or read-write. The structures in the table are defined as:: |
| 1113 | |
| 1114 | typedef struct PyMemberDef { |
| 1115 | char *name; |
| 1116 | int type; |
| 1117 | int offset; |
| 1118 | int flags; |
| 1119 | char *doc; |
| 1120 | } PyMemberDef; |
| 1121 | |
Georg Brandl | 9afde1c | 2007-11-01 20:32:30 +0000 | [diff] [blame] | 1122 | For each entry in the table, a :term:`descriptor` will be constructed and added to the |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1123 | type which will be able to extract a value from the instance structure. The |
| 1124 | :attr:`type` field should contain one of the type codes defined in the |
| 1125 | :file:`structmember.h` header; the value will be used to determine how to |
| 1126 | convert Python values to and from C values. The :attr:`flags` field is used to |
| 1127 | store flags which control how the attribute can be accessed. |
| 1128 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1129 | The following flag constants are defined in :file:`structmember.h`; they may be |
| 1130 | combined using bitwise-OR. |
| 1131 | |
| 1132 | +---------------------------+----------------------------------------------+ |
| 1133 | | Constant | Meaning | |
| 1134 | +===========================+==============================================+ |
| 1135 | | :const:`READONLY` | Never writable. | |
| 1136 | +---------------------------+----------------------------------------------+ |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1137 | | :const:`READ_RESTRICTED` | Not readable in restricted mode. | |
| 1138 | +---------------------------+----------------------------------------------+ |
| 1139 | | :const:`WRITE_RESTRICTED` | Not writable in restricted mode. | |
| 1140 | +---------------------------+----------------------------------------------+ |
| 1141 | | :const:`RESTRICTED` | Not readable or writable in restricted mode. | |
| 1142 | +---------------------------+----------------------------------------------+ |
| 1143 | |
| 1144 | .. index:: |
| 1145 | single: READONLY |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1146 | single: READ_RESTRICTED |
| 1147 | single: WRITE_RESTRICTED |
| 1148 | single: RESTRICTED |
| 1149 | |
| 1150 | An interesting advantage of using the :attr:`tp_members` table to build |
| 1151 | descriptors that are used at runtime is that any attribute defined this way can |
| 1152 | have an associated doc string simply by providing the text in the table. An |
| 1153 | application can use the introspection API to retrieve the descriptor from the |
| 1154 | class object, and get the doc string using its :attr:`__doc__` attribute. |
| 1155 | |
| 1156 | As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value |
| 1157 | of *NULL* is required. |
| 1158 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1159 | .. XXX Descriptors need to be explained in more detail somewhere, but not here. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1160 | |
Christian Heimes | 5b5e81c | 2007-12-31 16:14:33 +0000 | [diff] [blame] | 1161 | Descriptor objects have two handler functions which correspond to the |
| 1162 | \member{tp_getattro} and \member{tp_setattro} handlers. The |
| 1163 | \method{__get__()} handler is a function which is passed the descriptor, |
| 1164 | instance, and type objects, and returns the value of the attribute, or it |
| 1165 | returns \NULL{} and sets an exception. The \method{__set__()} handler is |
| 1166 | passed the descriptor, instance, type, and new value; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1167 | |
| 1168 | |
| 1169 | Type-specific Attribute Management |
| 1170 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ |
| 1171 | |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1172 | For simplicity, only the :c:type:`char\*` version will be demonstrated here; the |
| 1173 | type of the name parameter is the only difference between the :c:type:`char\*` |
| 1174 | and :c:type:`PyObject\*` flavors of the interface. This example effectively does |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1175 | the same thing as the generic example above, but does not use the generic |
Amaury Forgeot d'Arc | 87ce6d7 | 2008-07-02 22:59:48 +0000 | [diff] [blame] | 1176 | support added in Python 2.2. It explains how the handler functions are |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1177 | called, so that if you do need to extend their functionality, you'll understand |
| 1178 | what needs to be done. |
| 1179 | |
| 1180 | The :attr:`tp_getattr` handler is called when the object requires an attribute |
| 1181 | look-up. It is called in the same situations where the :meth:`__getattr__` |
| 1182 | method of a class would be called. |
| 1183 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1184 | Here is an example:: |
| 1185 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1186 | static PyObject * |
| 1187 | newdatatype_getattr(newdatatypeobject *obj, char *name) |
| 1188 | { |
Amaury Forgeot d'Arc | 87ce6d7 | 2008-07-02 22:59:48 +0000 | [diff] [blame] | 1189 | if (strcmp(name, "data") == 0) |
| 1190 | { |
| 1191 | return PyInt_FromLong(obj->data); |
| 1192 | } |
| 1193 | |
| 1194 | PyErr_Format(PyExc_AttributeError, |
| 1195 | "'%.50s' object has no attribute '%.400s'", |
Georg Brandl | 06788c9 | 2009-01-03 21:31:47 +0000 | [diff] [blame] | 1196 | tp->tp_name, name); |
Amaury Forgeot d'Arc | 87ce6d7 | 2008-07-02 22:59:48 +0000 | [diff] [blame] | 1197 | return NULL; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1198 | } |
| 1199 | |
| 1200 | The :attr:`tp_setattr` handler is called when the :meth:`__setattr__` or |
| 1201 | :meth:`__delattr__` method of a class instance would be called. When an |
| 1202 | attribute should be deleted, the third parameter will be *NULL*. Here is an |
| 1203 | example that simply raises an exception; if this were really all you wanted, the |
| 1204 | :attr:`tp_setattr` handler should be set to *NULL*. :: |
| 1205 | |
| 1206 | static int |
| 1207 | newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v) |
| 1208 | { |
| 1209 | (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name); |
| 1210 | return -1; |
| 1211 | } |
| 1212 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1213 | Object Comparison |
| 1214 | ----------------- |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1215 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1216 | :: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1217 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1218 | richcmpfunc tp_richcompare; |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1219 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1220 | The :attr:`tp_richcompare` handler is called when comparisons are needed. It is |
| 1221 | analogous to the :ref:`rich comparison methods <richcmpfuncs>`, like |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1222 | :meth:`__lt__`, and also called by :c:func:`PyObject_RichCompare` and |
| 1223 | :c:func:`PyObject_RichCompareBool`. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1224 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1225 | This function is called with two Python objects and the operator as arguments, |
| 1226 | where the operator is one of ``Py_EQ``, ``Py_NE``, ``Py_LE``, ``Py_GT``, |
| 1227 | ``Py_LT`` or ``Py_GT``. It should compare the two objects with respect to the |
| 1228 | specified operator and return ``Py_True`` or ``Py_False`` if the comparison is |
Georg Brandl | 6faee4e | 2010-09-21 14:48:28 +0000 | [diff] [blame] | 1229 | successful, ``Py_NotImplemented`` to indicate that comparison is not |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1230 | implemented and the other object's comparison method should be tried, or *NULL* |
| 1231 | if an exception was set. |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1232 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1233 | Here is a sample implementation, for a datatype that is considered equal if the |
| 1234 | size of an internal pointer is equal:: |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1235 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1236 | static int |
| 1237 | newdatatype_richcmp(PyObject *obj1, PyObject *obj2, int op) |
| 1238 | { |
| 1239 | PyObject *result; |
| 1240 | int c, size1, size2; |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1241 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1242 | /* code to make sure that both arguments are of type |
| 1243 | newdatatype omitted */ |
Georg Brandl | 48310cd | 2009-01-03 21:18:54 +0000 | [diff] [blame] | 1244 | |
Georg Brandl | 890a49a | 2009-03-31 18:56:38 +0000 | [diff] [blame] | 1245 | size1 = obj1->obj_UnderlyingDatatypePtr->size; |
| 1246 | size2 = obj2->obj_UnderlyingDatatypePtr->size; |
| 1247 | |
| 1248 | switch (op) { |
| 1249 | case Py_LT: c = size1 < size2; break; |
| 1250 | case Py_LE: c = size1 <= size2; break; |
| 1251 | case Py_EQ: c = size1 == size2; break; |
| 1252 | case Py_NE: c = size1 != size2; break; |
| 1253 | case Py_GT: c = size1 > size2; break; |
| 1254 | case Py_GE: c = size1 >= size2; break; |
| 1255 | } |
| 1256 | result = c ? Py_True : Py_False; |
| 1257 | Py_INCREF(result); |
| 1258 | return result; |
| 1259 | } |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1260 | |
| 1261 | |
| 1262 | Abstract Protocol Support |
| 1263 | ------------------------- |
| 1264 | |
| 1265 | Python supports a variety of *abstract* 'protocols;' the specific interfaces |
| 1266 | provided to use these interfaces are documented in :ref:`abstract`. |
| 1267 | |
| 1268 | |
| 1269 | A number of these abstract interfaces were defined early in the development of |
| 1270 | the Python implementation. In particular, the number, mapping, and sequence |
| 1271 | protocols have been part of Python since the beginning. Other protocols have |
| 1272 | been added over time. For protocols which depend on several handler routines |
| 1273 | from the type implementation, the older protocols have been defined as optional |
| 1274 | blocks of handlers referenced by the type object. For newer protocols there are |
| 1275 | additional slots in the main type object, with a flag bit being set to indicate |
| 1276 | that the slots are present and should be checked by the interpreter. (The flag |
| 1277 | bit does not indicate that the slot values are non-*NULL*. The flag may be set |
| 1278 | to indicate the presence of a slot, but a slot may still be unfilled.) :: |
| 1279 | |
Jesus Cea | 33b5769 | 2012-09-28 16:34:45 +0200 | [diff] [blame] | 1280 | PyNumberMethods *tp_as_number; |
| 1281 | PySequenceMethods *tp_as_sequence; |
| 1282 | PyMappingMethods *tp_as_mapping; |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1283 | |
| 1284 | If you wish your object to be able to act like a number, a sequence, or a |
| 1285 | mapping object, then you place the address of a structure that implements the C |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1286 | type :c:type:`PyNumberMethods`, :c:type:`PySequenceMethods`, or |
| 1287 | :c:type:`PyMappingMethods`, respectively. It is up to you to fill in this |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1288 | structure with appropriate values. You can find examples of the use of each of |
| 1289 | these in the :file:`Objects` directory of the Python source distribution. :: |
| 1290 | |
| 1291 | hashfunc tp_hash; |
| 1292 | |
| 1293 | This function, if you choose to provide it, should return a hash number for an |
| 1294 | instance of your data type. Here is a moderately pointless example:: |
| 1295 | |
| 1296 | static long |
| 1297 | newdatatype_hash(newdatatypeobject *obj) |
| 1298 | { |
| 1299 | long result; |
| 1300 | result = obj->obj_UnderlyingDatatypePtr->size; |
| 1301 | result = result * 3; |
| 1302 | return result; |
| 1303 | } |
| 1304 | |
| 1305 | :: |
| 1306 | |
| 1307 | ternaryfunc tp_call; |
| 1308 | |
| 1309 | This function is called when an instance of your data type is "called", for |
| 1310 | example, if ``obj1`` is an instance of your data type and the Python script |
| 1311 | contains ``obj1('hello')``, the :attr:`tp_call` handler is invoked. |
| 1312 | |
| 1313 | This function takes three arguments: |
| 1314 | |
| 1315 | #. *arg1* is the instance of the data type which is the subject of the call. If |
| 1316 | the call is ``obj1('hello')``, then *arg1* is ``obj1``. |
| 1317 | |
| 1318 | #. *arg2* is a tuple containing the arguments to the call. You can use |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1319 | :c:func:`PyArg_ParseTuple` to extract the arguments. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1320 | |
| 1321 | #. *arg3* is a dictionary of keyword arguments that were passed. If this is |
| 1322 | non-*NULL* and you support keyword arguments, use |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1323 | :c:func:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1324 | want to support keyword arguments and this is non-*NULL*, raise a |
| 1325 | :exc:`TypeError` with a message saying that keyword arguments are not supported. |
| 1326 | |
| 1327 | Here is a desultory example of the implementation of the call function. :: |
| 1328 | |
| 1329 | /* Implement the call function. |
| 1330 | * obj1 is the instance receiving the call. |
| 1331 | * obj2 is a tuple containing the arguments to the call, in this |
| 1332 | * case 3 strings. |
| 1333 | */ |
| 1334 | static PyObject * |
| 1335 | newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other) |
| 1336 | { |
| 1337 | PyObject *result; |
| 1338 | char *arg1; |
| 1339 | char *arg2; |
| 1340 | char *arg3; |
| 1341 | |
| 1342 | if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) { |
| 1343 | return NULL; |
| 1344 | } |
| 1345 | result = PyString_FromFormat( |
| 1346 | "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n", |
| 1347 | obj->obj_UnderlyingDatatypePtr->size, |
| 1348 | arg1, arg2, arg3); |
| 1349 | printf("\%s", PyString_AS_STRING(result)); |
| 1350 | return result; |
| 1351 | } |
| 1352 | |
Eli Bendersky | 49ac6f4 | 2012-02-27 19:18:35 +0200 | [diff] [blame] | 1353 | :: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1354 | |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1355 | /* Iterators */ |
| 1356 | getiterfunc tp_iter; |
| 1357 | iternextfunc tp_iternext; |
| 1358 | |
| 1359 | These functions provide support for the iterator protocol. Any object which |
| 1360 | wishes to support iteration over its contents (which may be generated during |
| 1361 | iteration) must implement the ``tp_iter`` handler. Objects which are returned |
| 1362 | by a ``tp_iter`` handler must implement both the ``tp_iter`` and ``tp_iternext`` |
| 1363 | handlers. Both handlers take exactly one parameter, the instance for which they |
| 1364 | are being called, and return a new reference. In the case of an error, they |
| 1365 | should set an exception and return *NULL*. |
| 1366 | |
| 1367 | For an object which represents an iterable collection, the ``tp_iter`` handler |
| 1368 | must return an iterator object. The iterator object is responsible for |
| 1369 | maintaining the state of the iteration. For collections which can support |
| 1370 | multiple iterators which do not interfere with each other (as lists and tuples |
| 1371 | do), a new iterator should be created and returned. Objects which can only be |
| 1372 | iterated over once (usually due to side effects of iteration) should implement |
| 1373 | this handler by returning a new reference to themselves, and should also |
| 1374 | implement the ``tp_iternext`` handler. File objects are an example of such an |
| 1375 | iterator. |
| 1376 | |
| 1377 | Iterator objects should implement both handlers. The ``tp_iter`` handler should |
| 1378 | return a new reference to the iterator (this is the same as the ``tp_iter`` |
| 1379 | handler for objects which can only be iterated over destructively). The |
| 1380 | ``tp_iternext`` handler should return a new reference to the next object in the |
| 1381 | iteration if there is one. If the iteration has reached the end, it may return |
| 1382 | *NULL* without setting an exception or it may set :exc:`StopIteration`; avoiding |
| 1383 | the exception can yield slightly better performance. If an actual error occurs, |
| 1384 | it should set an exception and return *NULL*. |
| 1385 | |
| 1386 | |
| 1387 | .. _weakref-support: |
| 1388 | |
| 1389 | Weak Reference Support |
| 1390 | ---------------------- |
| 1391 | |
| 1392 | One of the goals of Python's weak-reference implementation is to allow any type |
| 1393 | to participate in the weak reference mechanism without incurring the overhead on |
| 1394 | those objects which do not benefit by weak referencing (such as numbers). |
| 1395 | |
| 1396 | For an object to be weakly referencable, the extension must include a |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1397 | :c:type:`PyObject\*` field in the instance structure for the use of the weak |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1398 | reference mechanism; it must be initialized to *NULL* by the object's |
| 1399 | constructor. It must also set the :attr:`tp_weaklistoffset` field of the |
| 1400 | corresponding type object to the offset of the field. For example, the instance |
| 1401 | type is defined with the following structure:: |
| 1402 | |
| 1403 | typedef struct { |
| 1404 | PyObject_HEAD |
| 1405 | PyClassObject *in_class; /* The class object */ |
| 1406 | PyObject *in_dict; /* A dictionary */ |
| 1407 | PyObject *in_weakreflist; /* List of weak references */ |
| 1408 | } PyInstanceObject; |
| 1409 | |
| 1410 | The statically-declared type object for instances is defined this way:: |
| 1411 | |
| 1412 | PyTypeObject PyInstance_Type = { |
Georg Brandl | ec12e82 | 2009-02-27 17:11:23 +0000 | [diff] [blame] | 1413 | PyVarObject_HEAD_INIT(&PyType_Type, 0) |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1414 | 0, |
| 1415 | "module.instance", |
| 1416 | |
| 1417 | /* Lots of stuff omitted for brevity... */ |
| 1418 | |
| 1419 | Py_TPFLAGS_DEFAULT, /* tp_flags */ |
| 1420 | 0, /* tp_doc */ |
| 1421 | 0, /* tp_traverse */ |
| 1422 | 0, /* tp_clear */ |
| 1423 | 0, /* tp_richcompare */ |
| 1424 | offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */ |
| 1425 | }; |
| 1426 | |
| 1427 | The type constructor is responsible for initializing the weak reference list to |
| 1428 | *NULL*:: |
| 1429 | |
| 1430 | static PyObject * |
| 1431 | instance_new() { |
| 1432 | /* Other initialization stuff omitted for brevity */ |
| 1433 | |
| 1434 | self->in_weakreflist = NULL; |
| 1435 | |
| 1436 | return (PyObject *) self; |
| 1437 | } |
| 1438 | |
| 1439 | The only further addition is that the destructor needs to call the weak |
Antoine Pitrou | 1377522 | 2012-06-15 19:11:31 +0200 | [diff] [blame] | 1440 | reference manager to clear any weak references. This is only required if the |
| 1441 | weak reference list is non-*NULL*:: |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1442 | |
| 1443 | static void |
| 1444 | instance_dealloc(PyInstanceObject *inst) |
| 1445 | { |
| 1446 | /* Allocate temporaries if needed, but do not begin |
| 1447 | destruction just yet. |
| 1448 | */ |
| 1449 | |
| 1450 | if (inst->in_weakreflist != NULL) |
| 1451 | PyObject_ClearWeakRefs((PyObject *) inst); |
| 1452 | |
| 1453 | /* Proceed with object destruction normally. */ |
| 1454 | } |
| 1455 | |
| 1456 | |
| 1457 | More Suggestions |
| 1458 | ---------------- |
| 1459 | |
| 1460 | Remember that you can omit most of these functions, in which case you provide |
| 1461 | ``0`` as a value. There are type definitions for each of the functions you must |
| 1462 | provide. They are in :file:`object.h` in the Python include directory that |
| 1463 | comes with the source distribution of Python. |
| 1464 | |
| 1465 | In order to learn how to implement any specific method for your new data type, |
Mark Dickinson | 9f98926 | 2009-02-02 21:29:40 +0000 | [diff] [blame] | 1466 | do the following: Download and unpack the Python source distribution. Go to |
| 1467 | the :file:`Objects` directory, then search the C source files for ``tp_`` plus |
| 1468 | the function you want (for example, ``tp_richcompare``). You will find examples |
| 1469 | of the function you want to implement. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1470 | |
| 1471 | When you need to verify that an object is an instance of the type you are |
Georg Brandl | 60203b4 | 2010-10-06 10:11:56 +0000 | [diff] [blame] | 1472 | implementing, use the :c:func:`PyObject_TypeCheck` function. A sample of its use |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1473 | might be something like the following:: |
| 1474 | |
| 1475 | if (! PyObject_TypeCheck(some_object, &MyType)) { |
| 1476 | PyErr_SetString(PyExc_TypeError, "arg #1 not a mything"); |
| 1477 | return NULL; |
| 1478 | } |
| 1479 | |
| 1480 | .. rubric:: Footnotes |
| 1481 | |
| 1482 | .. [#] This is true when we know that the object is a basic type, like a string or a |
| 1483 | float. |
| 1484 | |
| 1485 | .. [#] We relied on this in the :attr:`tp_dealloc` handler in this example, because our |
| 1486 | type doesn't support garbage collection. Even if a type supports garbage |
| 1487 | collection, there are calls that can be made to "untrack" the object from |
| 1488 | garbage collection, however, these calls are advanced and not covered here. |
| 1489 | |
| 1490 | .. [#] We now know that the first and last members are strings, so perhaps we could be |
| 1491 | less careful about decrementing their reference counts, however, we accept |
| 1492 | instances of string subclasses. Even though deallocating normal strings won't |
| 1493 | call back into our objects, we can't guarantee that deallocating an instance of |
Christian Heimes | f75b290 | 2008-03-16 17:29:44 +0000 | [diff] [blame] | 1494 | a string subclass won't call back into our objects. |
Georg Brandl | 116aa62 | 2007-08-15 14:28:22 +0000 | [diff] [blame] | 1495 | |
| 1496 | .. [#] Even in the third version, we aren't guaranteed to avoid cycles. Instances of |
| 1497 | string subclasses are allowed and string subclasses could allow cycles even if |
| 1498 | normal strings don't. |
| 1499 | |