rest25/extending/newtypes.rst => rest262/extending/newtypes.rst
42them from things like ``[].append`` (which we call "object methods").
43
44So, if you want to define a new object type, you need to create a new type
45object.
46
47This sort of thing can only be explained by example, so here's a minimal, but
48complete, module that defines a new type:
49
n50- 
51-.. include:: ../includes/noddy.c
50+.. literalinclude:: ../includes/noddy.c
52-   :literal:
51+ 
53
54Now that's quite a bit to take in at once, but hopefully bits will seem familiar
55from the last chapter.
56
57The first bit that will be new is::
58
59   typedef struct {
60       PyObject_HEAD
228in a file called :file:`setup.py`; then typing ::
229
230   $ python setup.py build
231
232at a shell should produce a file :file:`noddy.so` in a subdirectory; move to
233that directory and fire up Python --- you should be able to ``import noddy`` and
234play around with Noddy objects.
235
n236-.. % $ <-- bow to font-lock  ;-(
237- 
238That wasn't so hard, was it?
239
240Of course, the current Noddy type is pretty uninteresting. It has no data and
241doesn't do anything. It can't even be subclassed.
242
243
244Adding data and methods to the Basic example
245--------------------------------------------
246
247Let's expend the basic example to add some data and methods.  Let's also make
248the type usable as a base class. We'll create a new module, :mod:`noddy2` that
249adds these capabilities:
250
n251- 
252-.. include:: ../includes/noddy2.c
248+.. literalinclude:: ../includes/noddy2.c
253-   :literal:
249+ 
254
255This version of the module has a number of changes.
256
257We've added an extra include::
258
259   #include "structmember.h"
260
261This include provides declarations that we use to handle attributes, as
427* when we absolutely know that the reference count is greater than 1
428
429* when we know that deallocation of the object [#]_ will not cause any calls
430  back into our type's code
431
432* when decrementing a reference count in a :attr:`tp_dealloc` handler when
433  garbage-collections is not supported [#]_
434
n435-*
436- 
437-We want to want to expose our instance variables as attributes. There are a
431+We want to expose our instance variables as attributes. There are a
438number of ways to do that. The simplest way is to define member definitions::
439
440   static PyMemberDef Noddy_members[] = {
441       {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
442        "first name"},
443       {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
444        "last name"},
445       {"number", T_INT, offsetof(Noddy, number), 0,
554--------------------------------------------
555
556In this section, we'll provide finer control over how the :attr:`first` and
557:attr:`last` attributes are set in the :class:`Noddy` example. In the previous
558version of our module, the instance variables :attr:`first` and :attr:`last`
559could be set to non-string values or even deleted. We want to make sure that
560these attributes always contain strings.
561
n562- 
563-.. include:: ../includes/noddy3.c
556+.. literalinclude:: ../includes/noddy3.c
564-   :literal:
557+ 
565
566To provide greater control, over the :attr:`first` and :attr:`last` attributes,
567we'll use custom getter and setter functions.  Here are the functions for
568getting and setting the :attr:`first` attribute::
569
570   Noddy_getfirst(Noddy *self, void *closure)
571   {
572       Py_INCREF(self->first);
618        NULL},
619       {NULL}  /* Sentinel */
620   };
621
622and register it in the :attr:`tp_getset` slot::
623
624   Noddy_getseters,           /* tp_getset */
625
n626-to register out attribute getters and setters.
n619+to register our attribute getters and setters.
627
628The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned
629above. In this case, we aren't using the closure, so we just pass *NULL*.
630
631We also remove the member definitions for these attributes::
632
633   static PyMemberDef Noddy_members[] = {
634       {"number", T_INT, offsetof(Noddy, number), 0,
700object to be stored in the :attr:`first` or :attr:`last` attributes. [#]_ This
701means that :class:`Noddy` objects can participate in cycles::
702
703   >>> import noddy2
704   >>> n = noddy2.Noddy()
705   >>> l = [n]
706   >>> n.first = l
707
n708-This is pretty silly, but it gives us an excuse to add support for the cyclic-
n701+This is pretty silly, but it gives us an excuse to add support for the
709-garbage collector to the :class:`Noddy` example.  To support cyclic garbage
702+cyclic-garbage collector to the :class:`Noddy` example.  To support cyclic
710-collection, types need to fill two slots and set a class flag that enables these
703+garbage collection, types need to fill two slots and set a class flag that
711-slots:
704+enables these slots:
712
n713- 
714-.. include:: ../includes/noddy4.c
706+.. literalinclude:: ../includes/noddy4.c
715-   :literal:
707+ 
716
717The traversal method provides access to subobjects that could participate in
718cycles::
719
720   static int
721   Noddy_traverse(Noddy *self, visitproc visit, void *arg)
722   {
723       int vret;
813
814   Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
815
816That's pretty much it.  If we had written custom :attr:`tp_alloc` or
817:attr:`tp_free` slots, we'd need to modify them for cyclic-garbage collection.
818Most extensions will use the versions automatically provided.
819
820
n813+Subclassing other types
814+-----------------------
815+ 
816+It is possible to create new extension types that are derived from existing
817+types. It is easiest to inherit from the built in types, since an extension can
818+easily use the :class:`PyTypeObject` it needs. It can be difficult to share
819+these :class:`PyTypeObject` structures between extension modules.
820+ 
821+In this example we will create a :class:`Shoddy` type that inherits from the
822+builtin :class:`list` type. The new type will be completely compatible with
823+regular lists, but will have an additional :meth:`increment` method that
824+increases an internal counter. ::
825+ 
826+   >>> import shoddy
827+   >>> s = shoddy.Shoddy(range(3))
828+   >>> s.extend(s)
829+   >>> print len(s)
830+   6
831+   >>> print s.increment()
832+   1
833+   >>> print s.increment()
834+   2
835+ 
836+.. literalinclude:: ../includes/shoddy.c
837+ 
838+ 
839+As you can see, the source code closely resembles the :class:`Noddy` examples in
840+previous sections. We will break down the main differences between them. ::
841+ 
842+   typedef struct {
843+       PyListObject list;
844+       int state;
845+   } Shoddy;
846+ 
847+The primary difference for derived type objects is that the base type's object
848+structure must be the first value. The base type will already include the
849+:cfunc:`PyObject_HEAD` at the beginning of its structure.
850+ 
851+When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can
852+be safely cast to both *PyListObject\** and *Shoddy\**. ::
853+ 
854+   static int
855+   Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
856+   {
857+       if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
858+          return -1;
859+       self->state = 0;
860+       return 0;
861+   }
862+ 
863+In the :attr:`__init__` method for our type, we can see how to call through to
864+the :attr:`__init__` method of the base type.
865+ 
866+This pattern is important when writing a type with custom :attr:`new` and
867+:attr:`dealloc` methods. The :attr:`new` method should not actually create the
868+memory for the object with :attr:`tp_alloc`, that will be handled by the base
869+class when calling its :attr:`tp_new`.
870+ 
871+When filling out the :cfunc:`PyTypeObject` for the :class:`Shoddy` type, you see
872+a slot for :cfunc:`tp_base`. Due to cross platform compiler issues, you can't
873+fill that field directly with the :cfunc:`PyList_Type`; it can be done later in
874+the module's :cfunc:`init` function. ::
875+ 
876+   PyMODINIT_FUNC
877+   initshoddy(void)
878+   {
879+       PyObject *m;
880+ 
881+       ShoddyType.tp_base = &PyList_Type;
882+       if (PyType_Ready(&ShoddyType) < 0)
883+           return;
884+ 
885+       m = Py_InitModule3("shoddy", NULL, "Shoddy module");
886+       if (m == NULL)
887+           return;
888+ 
889+       Py_INCREF(&ShoddyType);
890+       PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
891+   }
892+ 
893+Before calling :cfunc:`PyType_Ready`, the type structure must have the
894+:attr:`tp_base` slot filled in. When we are deriving a new type, it is not
895+necessary to fill out the :attr:`tp_alloc` slot with :cfunc:`PyType_GenericNew`
896+-- the allocate function from the base type will be inherited.
897+ 
898+After that, calling :cfunc:`PyType_Ready` and adding the type object to the
899+module is the same as with the basic :class:`Noddy` examples.
900+ 
901+ 
821.. _dnt-type-methods:
822
823Type Methods
824============
825
826This section aims to give a quick fly-by on the various type methods you can
827implement and what they do.
828
829Here is the definition of :ctype:`PyTypeObject`, with some fields only used in
830debug builds omitted:
831
n832- 
833-.. include:: ../includes/typestruct.h
913+.. literalinclude:: ../includes/typestruct.h
834-   :literal:
914+ 
835
836Now that's a *lot* of methods.  Don't worry too much though - if you have a type
837you want to define, the chances are very good that you will only implement a
838handful of these.
839
840As you probably expect by now, we're going to go over this and give more
841information about the various handlers.  We won't go in the order they are
842defined in the structure, because there is a lot of historical baggage that
1062
1063#. No special processing is needed to record that an attribute was looked up or
1064   set, nor do actions need to be taken based on the value.
1065
1066Note that this list does not place any restrictions on the values of the
1067attributes, when the values are computed, or how relevant data is stored.
1068
1069When :cfunc:`PyType_Ready` is called, it uses three tables referenced by the
n1070-type object to create *descriptors* which are placed in the dictionary of the
n1150+type object to create :term:`descriptor`\s which are placed in the dictionary of the
1071type object.  Each descriptor controls access to one attribute of the instance
1072object.  Each of the tables is optional; if all three are *NULL*, instances of
1073the type will only have attributes that are inherited from their base type, and
1074should leave the :attr:`tp_getattro` and :attr:`tp_setattro` fields *NULL* as
1075well, allowing the base type to handle attributes.
1076
1077The tables are declared as three fields of the type object::
1078
1082
1083If :attr:`tp_methods` is not *NULL*, it must refer to an array of
1084:ctype:`PyMethodDef` structures.  Each entry in the table is an instance of this
1085structure::
1086
1087   typedef struct PyMethodDef {
1088       char        *ml_name;       /* method name */
1089       PyCFunction  ml_meth;       /* implementation function */
n1090-       int               ml_flags;      /* flags */
n1170+       int          ml_flags;      /* flags */
1091       char        *ml_doc;        /* docstring */
1092   } PyMethodDef;
1093
1094One entry should be defined for each method provided by the type; no entries are
1095needed for methods inherited from a base type.  One additional entry is needed
1096at the end; it is a sentinel that marks the end of the array.  The
1097:attr:`ml_name` field of the sentinel must be *NULL*.
1098
1106   typedef struct PyMemberDef {
1107       char *name;
1108       int   type;
1109       int   offset;
1110       int   flags;
1111       char *doc;
1112   } PyMemberDef;
1113
n1114-For each entry in the table, a descriptor will be constructed and added to the
n1194+For each entry in the table, a :term:`descriptor` will be constructed and added to the
1115type which will be able to extract a value from the instance structure.  The
1116:attr:`type` field should contain one of the type codes defined in the
1117:file:`structmember.h` header; the value will be used to determine how to
1118convert Python values to and from C values.  The :attr:`flags` field is used to
1119store flags which control how the attribute can be accessed.
1120
1121XXX Need to move some of this to a shared section!
1122
1148descriptors that are used at runtime is that any attribute defined this way can
1149have an associated doc string simply by providing the text in the table.  An
1150application can use the introspection API to retrieve the descriptor from the
1151class object, and get the doc string using its :attr:`__doc__` attribute.
1152
1153As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value
1154of *NULL* is required.
1155
n1156-.. % XXX Descriptors need to be explained in more detail somewhere, but
n1236+.. XXX Descriptors need to be explained in more detail somewhere, but not here.
1157-.. % not here.
1237+ 
1158-.. % 
1159-.. % Descriptor objects have two handler functions which correspond to
1238+   Descriptor objects have two handler functions which correspond to the
1160-.. % the \member{tp_getattro} and \member{tp_setattro} handlers.  The
1239+   \member{tp_getattro} and \member{tp_setattro} handlers.  The
1161-.. % \method{__get__()} handler is a function which is passed the
1240+   \method{__get__()} handler is a function which is passed the descriptor,
1162-.. % descriptor, instance, and type objects, and returns the value of the
1241+   instance, and type objects, and returns the value of the attribute, or it
1163-.. % attribute, or it returns \NULL{} and sets an exception.  The
1242+   returns \NULL{} and sets an exception.  The \method{__set__()} handler is
1164-.. % \method{__set__()} handler is passed the descriptor, instance, type,
1243+   passed the descriptor, instance, type, and new value;
1165-.. % and new value;
1166
1167
1168Type-specific Attribute Management
1169^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1170
1171For simplicity, only the :ctype:`char\*` version will be demonstrated here; the
1172type of the name parameter is the only difference between the :ctype:`char\*`
1173and :ctype:`PyObject\*` flavors of the interface. This example effectively does
1262       return result;
1263   }
1264
1265
1266Abstract Protocol Support
1267-------------------------
1268
1269Python supports a variety of *abstract* 'protocols;' the specific interfaces
n1270-provided to use these interfaces are documented in the Python/C API Reference
n1348+provided to use these interfaces are documented in :ref:`abstract`.
1271-Manual (XXX reference: ../api/api.html) in the chapter "Abstract Objects Layer
1349+ 
1272-(XXX reference: ../api/abstract.html)."
1273
1274A number of these abstract interfaces were defined early in the development of
1275the Python implementation.  In particular, the number, mapping, and sequence
1276protocols have been part of Python since the beginning.  Other protocols have
1277been added over time.  For protocols which depend on several handler routines
1278from the type implementation, the older protocols have been defined as optional
1279blocks of handlers referenced by the type object.  For newer protocols there are
1280additional slots in the main type object, with a flag bit being set to indicate
1493   type doesn't support garbage collection. Even if a type supports garbage
1494   collection, there are calls that can be made to "untrack" the object from
1495   garbage collection, however, these calls are advanced and not covered here.
1496
1497.. [#] We now know that the first and last members are strings, so perhaps we could be
1498   less careful about decrementing their reference counts, however, we accept
1499   instances of string subclasses. Even though deallocating normal strings won't
1500   call back into our objects, we can't guarantee that deallocating an instance of
t1501-   a string subclass won't. call back into out objects.
t1578+   a string subclass won't call back into our objects.
1502
1503.. [#] Even in the third version, we aren't guaranteed to avoid cycles.  Instances of
1504   string subclasses are allowed and string subclasses could allow cycles even if
1505   normal strings don't.
1506
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op