4 .. _defining-new-types:
10 .. sectionauthor:: Michael Hudson <mwh@python.net>
11 .. sectionauthor:: Dave Kuhlman <dkuhlman@rexx.com>
12 .. sectionauthor:: Jim Fulton <jim@zope.com>
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.
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.
24 The way new types are defined changed dramatically (and for the better) in
25 Python 2.2. This document documents how to define new types for Python 2.2 and
26 later. If you need to support older versions of Python, you will need to refer
27 to `older versions of this documentation
28 <http://www.python.org/doc/versions/>`_.
36 The Python runtime sees all Python objects as variables of type
37 :ctype:`PyObject\*`. A :ctype:`PyObject` is not a very magnificent object - it
38 just contains the refcount and a pointer to the object's "type object". This is
39 where the action is; the type object determines which (C) functions get called
40 when, for instance, an attribute gets looked up on an object or it is multiplied
41 by another object. These C functions are called "type methods" to distinguish
42 them from things like ``[].append`` (which we call "object methods").
44 So, if you want to define a new object type, you need to create a new type
47 This sort of thing can only be explained by example, so here's a minimal, but
48 complete, module that defines a new type:
50 .. literalinclude:: ../includes/noddy.c
53 Now that's quite a bit to take in at once, but hopefully bits will seem familiar
54 from the last chapter.
56 The first bit that will be new is::
62 This is what a Noddy object will contain---in this case, nothing more than every
63 Python object contains, namely a refcount and a pointer to a type object. These
64 are the fields the ``PyObject_HEAD`` macro brings in. The reason for the macro
65 is to standardize the layout and to enable special debugging fields in debug
66 builds. Note that there is no semicolon after the ``PyObject_HEAD`` macro; one
67 is included in the macro definition. Be wary of adding one by accident; it's
68 easy to do from habit, and your compiler might not complain, but someone else's
69 probably will! (On Windows, MSVC is known to call this an error and refuse to
72 For contrast, let's take a look at the corresponding definition for standard
80 Moving on, we come to the crunch --- the type object. ::
82 static PyTypeObject noddy_NoddyType = {
83 PyObject_HEAD_INIT(NULL)
85 "noddy.Noddy", /*tp_name*/
86 sizeof(noddy_NoddyObject), /*tp_basicsize*/
103 Py_TPFLAGS_DEFAULT, /*tp_flags*/
104 "Noddy objects", /* tp_doc */
107 Now if you go and look up the definition of :ctype:`PyTypeObject` in
108 :file:`object.h` you'll see that it has many more fields that the definition
109 above. The remaining fields will be filled with zeros by the C compiler, and
110 it's common practice to not specify them explicitly unless you need them.
112 This is so important that we're going to pick the top of it apart still
115 PyObject_HEAD_INIT(NULL)
117 This line is a bit of a wart; what we'd like to write is::
119 PyObject_HEAD_INIT(&PyType_Type)
121 as the type of a type object is "type", but this isn't strictly conforming C and
122 some compilers complain. Fortunately, this member will be filled in for us by
123 :cfunc:`PyType_Ready`. ::
127 The :attr:`ob_size` field of the header is not used; its presence in the type
128 structure is a historical artifact that is maintained for binary compatibility
129 with extension modules compiled for older versions of Python. Always set this
132 "noddy.Noddy", /* tp_name */
134 The name of our type. This will appear in the default textual representation of
135 our objects and in some error messages, for example::
137 >>> "" + noddy.new_noddy()
138 Traceback (most recent call last):
139 File "<stdin>", line 1, in ?
140 TypeError: cannot add type "noddy.Noddy" to string
142 Note that the name is a dotted name that includes both the module name and the
143 name of the type within the module. The module in this case is :mod:`noddy` and
144 the type is :class:`Noddy`, so we set the type name to :class:`noddy.Noddy`. ::
146 sizeof(noddy_NoddyObject), /* tp_basicsize */
148 This is so that Python knows how much memory to allocate when you call
149 :cfunc:`PyObject_New`.
153 If you want your type to be subclassable from Python, and your type has the same
154 :attr:`tp_basicsize` as its base type, you may have problems with multiple
155 inheritance. A Python subclass of your type will have to list your type first
156 in its :attr:`__bases__`, or else it will not be able to call your type's
157 :meth:`__new__` method without getting an error. You can avoid this problem by
158 ensuring that your type has a larger value for :attr:`tp_basicsize` than its
159 base type does. Most of the time, this will be true anyway, because either your
160 base type will be :class:`object`, or else you will be adding data members to
161 your base type, and therefore increasing its size.
167 This has to do with variable length objects like lists and strings. Ignore this
170 Skipping a number of type methods that we don't provide, we set the class flags
171 to :const:`Py_TPFLAGS_DEFAULT`. ::
173 Py_TPFLAGS_DEFAULT, /*tp_flags*/
175 All types should include this constant in their flags. It enables all of the
176 members defined by the current version of Python.
178 We provide a doc string for the type in :attr:`tp_doc`. ::
180 "Noddy objects", /* tp_doc */
182 Now we get into the type methods, the things that make your objects different
183 from the others. We aren't going to implement any of these in this version of
184 the module. We'll expand this example later to have more interesting behavior.
186 For now, all we want to be able to do is to create new :class:`Noddy` objects.
187 To enable object creation, we have to provide a :attr:`tp_new` implementation.
188 In this case, we can just use the default implementation provided by the API
189 function :cfunc:`PyType_GenericNew`. We'd like to just assign this to the
190 :attr:`tp_new` slot, but we can't, for portability sake, On some platforms or
191 compilers, we can't statically initialize a structure member with a function
192 defined in another C module, so, instead, we'll assign the :attr:`tp_new` slot
193 in the module initialization function just before calling
194 :cfunc:`PyType_Ready`::
196 noddy_NoddyType.tp_new = PyType_GenericNew;
197 if (PyType_Ready(&noddy_NoddyType) < 0)
200 All the other type methods are *NULL*, so we'll go over them later --- that's
203 Everything else in the file should be familiar, except for some code in
206 if (PyType_Ready(&noddy_NoddyType) < 0)
209 This initializes the :class:`Noddy` type, filing in a number of members,
210 including :attr:`ob_type` that we initially set to *NULL*. ::
212 PyModule_AddObject(m, "Noddy", (PyObject *)&noddy_NoddyType);
214 This adds the type to the module dictionary. This allows us to create
215 :class:`Noddy` instances by calling the :class:`Noddy` class::
218 >>> mynoddy = noddy.Noddy()
220 That's it! All that remains is to build it; put the above code in a file called
221 :file:`noddy.c` and ::
223 from distutils.core import setup, Extension
224 setup(name="noddy", version="1.0",
225 ext_modules=[Extension("noddy", ["noddy.c"])])
227 in a file called :file:`setup.py`; then typing ::
229 $ python setup.py build
231 at a shell should produce a file :file:`noddy.so` in a subdirectory; move to
232 that directory and fire up Python --- you should be able to ``import noddy`` and
233 play around with Noddy objects.
235 That wasn't so hard, was it?
237 Of course, the current Noddy type is pretty uninteresting. It has no data and
238 doesn't do anything. It can't even be subclassed.
241 Adding data and methods to the Basic example
242 --------------------------------------------
244 Let's expend the basic example to add some data and methods. Let's also make
245 the type usable as a base class. We'll create a new module, :mod:`noddy2` that
246 adds these capabilities:
248 .. literalinclude:: ../includes/noddy2.c
251 This version of the module has a number of changes.
253 We've added an extra include::
255 #include "structmember.h"
257 This include provides declarations that we use to handle attributes, as
258 described a bit later.
260 The name of the :class:`Noddy` object structure has been shortened to
261 :class:`Noddy`. The type object name has been shortened to :class:`NoddyType`.
263 The :class:`Noddy` type now has three data attributes, *first*, *last*, and
264 *number*. The *first* and *last* variables are Python strings containing first
265 and last names. The *number* attribute is an integer.
267 The object structure is updated accordingly::
276 Because we now have data to manage, we have to be more careful about object
277 allocation and deallocation. At a minimum, we need a deallocation method::
280 Noddy_dealloc(Noddy* self)
282 Py_XDECREF(self->first);
283 Py_XDECREF(self->last);
284 self->ob_type->tp_free((PyObject*)self);
287 which is assigned to the :attr:`tp_dealloc` member::
289 (destructor)Noddy_dealloc, /*tp_dealloc*/
291 This method decrements the reference counts of the two Python attributes. We use
292 :cfunc:`Py_XDECREF` here because the :attr:`first` and :attr:`last` members
293 could be *NULL*. It then calls the :attr:`tp_free` member of the object's type
294 to free the object's memory. Note that the object's type might not be
295 :class:`NoddyType`, because the object may be an instance of a subclass.
297 We want to make sure that the first and last names are initialized to empty
298 strings, so we provide a new method::
301 Noddy_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
305 self = (Noddy *)type->tp_alloc(type, 0);
307 self->first = PyString_FromString("");
308 if (self->first == NULL)
314 self->last = PyString_FromString("");
315 if (self->last == NULL)
324 return (PyObject *)self;
327 and install it in the :attr:`tp_new` member::
329 Noddy_new, /* tp_new */
331 The new member is responsible for creating (as opposed to initializing) objects
332 of the type. It is exposed in Python as the :meth:`__new__` method. See the
333 paper titled "Unifying types and classes in Python" for a detailed discussion of
334 the :meth:`__new__` method. One reason to implement a new method is to assure
335 the initial values of instance variables. In this case, we use the new method
336 to make sure that the initial values of the members :attr:`first` and
337 :attr:`last` are not *NULL*. If we didn't care whether the initial values were
338 *NULL*, we could have used :cfunc:`PyType_GenericNew` as our new method, as we
339 did before. :cfunc:`PyType_GenericNew` initializes all of the instance variable
342 The new method is a static method that is passed the type being instantiated and
343 any arguments passed when the type was called, and that returns the new object
344 created. New methods always accept positional and keyword arguments, but they
345 often ignore the arguments, leaving the argument handling to initializer
346 methods. Note that if the type supports subclassing, the type passed may not be
347 the type being defined. The new method calls the tp_alloc slot to allocate
348 memory. We don't fill the :attr:`tp_alloc` slot ourselves. Rather
349 :cfunc:`PyType_Ready` fills it for us by inheriting it from our base class,
350 which is :class:`object` by default. Most types use the default allocation.
354 If you are creating a co-operative :attr:`tp_new` (one that calls a base type's
355 :attr:`tp_new` or :meth:`__new__`), you must *not* try to determine what method
356 to call using method resolution order at runtime. Always statically determine
357 what type you are going to call, and call its :attr:`tp_new` directly, or via
358 ``type->tp_base->tp_new``. If you do not do this, Python subclasses of your
359 type that also inherit from other Python-defined classes may not work correctly.
360 (Specifically, you may not be able to create instances of such subclasses
361 without getting a :exc:`TypeError`.)
363 We provide an initialization function::
366 Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
368 PyObject *first=NULL, *last=NULL, *tmp;
370 static char *kwlist[] = {"first", "last", "number", NULL};
372 if (! PyArg_ParseTupleAndKeywords(args, kwds, "|OOi", kwlist,
394 by filling the :attr:`tp_init` slot. ::
396 (initproc)Noddy_init, /* tp_init */
398 The :attr:`tp_init` slot is exposed in Python as the :meth:`__init__` method. It
399 is used to initialize an object after it's created. Unlike the new method, we
400 can't guarantee that the initializer is called. The initializer isn't called
401 when unpickling objects and it can be overridden. Our initializer accepts
402 arguments to provide initial values for our instance. Initializers always accept
403 positional and keyword arguments.
405 Initializers can be called multiple times. Anyone can call the :meth:`__init__`
406 method on our objects. For this reason, we have to be extra careful when
407 assigning the new values. We might be tempted, for example to assign the
408 :attr:`first` member like this::
411 Py_XDECREF(self->first);
416 But this would be risky. Our type doesn't restrict the type of the
417 :attr:`first` member, so it could be any kind of object. It could have a
418 destructor that causes code to be executed that tries to access the
419 :attr:`first` member. To be paranoid and protect ourselves against this
420 possibility, we almost always reassign members before decrementing their
421 reference counts. When don't we have to do this?
423 * when we absolutely know that the reference count is greater than 1
425 * when we know that deallocation of the object [#]_ will not cause any calls
426 back into our type's code
428 * when decrementing a reference count in a :attr:`tp_dealloc` handler when
429 garbage-collections is not supported [#]_
431 We want to expose our instance variables as attributes. There are a
432 number of ways to do that. The simplest way is to define member definitions::
434 static PyMemberDef Noddy_members[] = {
435 {"first", T_OBJECT_EX, offsetof(Noddy, first), 0,
437 {"last", T_OBJECT_EX, offsetof(Noddy, last), 0,
439 {"number", T_INT, offsetof(Noddy, number), 0,
441 {NULL} /* Sentinel */
444 and put the definitions in the :attr:`tp_members` slot::
446 Noddy_members, /* tp_members */
448 Each member definition has a member name, type, offset, access flags and
449 documentation string. See the "Generic Attribute Management" section below for
452 A disadvantage of this approach is that it doesn't provide a way to restrict the
453 types of objects that can be assigned to the Python attributes. We expect the
454 first and last names to be strings, but any Python objects can be assigned.
455 Further, the attributes can be deleted, setting the C pointers to *NULL*. Even
456 though we can make sure the members are initialized to non-*NULL* values, the
457 members can be set to *NULL* if the attributes are deleted.
459 We define a single method, :meth:`name`, that outputs the objects name as the
460 concatenation of the first and last names. ::
463 Noddy_name(Noddy* self)
465 static PyObject *format = NULL;
466 PyObject *args, *result;
468 if (format == NULL) {
469 format = PyString_FromString("%s %s");
474 if (self->first == NULL) {
475 PyErr_SetString(PyExc_AttributeError, "first");
479 if (self->last == NULL) {
480 PyErr_SetString(PyExc_AttributeError, "last");
484 args = Py_BuildValue("OO", self->first, self->last);
488 result = PyString_Format(format, args);
494 The method is implemented as a C function that takes a :class:`Noddy` (or
495 :class:`Noddy` subclass) instance as the first argument. Methods always take an
496 instance as the first argument. Methods often take positional and keyword
497 arguments as well, but in this cased we don't take any and don't need to accept
498 a positional argument tuple or keyword argument dictionary. This method is
499 equivalent to the Python method::
502 return "%s %s" % (self.first, self.last)
504 Note that we have to check for the possibility that our :attr:`first` and
505 :attr:`last` members are *NULL*. This is because they can be deleted, in which
506 case they are set to *NULL*. It would be better to prevent deletion of these
507 attributes and to restrict the attribute values to be strings. We'll see how to
508 do that in the next section.
510 Now that we've defined the method, we need to create an array of method
513 static PyMethodDef Noddy_methods[] = {
514 {"name", (PyCFunction)Noddy_name, METH_NOARGS,
515 "Return the name, combining the first and last name"
517 {NULL} /* Sentinel */
520 and assign them to the :attr:`tp_methods` slot::
522 Noddy_methods, /* tp_methods */
524 Note that we used the :const:`METH_NOARGS` flag to indicate that the method is
527 Finally, we'll make our type usable as a base class. We've written our methods
528 carefully so far so that they don't make any assumptions about the type of the
529 object being created or used, so all we need to do is to add the
530 :const:`Py_TPFLAGS_BASETYPE` to our class flag definition::
532 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
534 We rename :cfunc:`initnoddy` to :cfunc:`initnoddy2` and update the module name
535 passed to :cfunc:`Py_InitModule3`.
537 Finally, we update our :file:`setup.py` file to build the new module::
539 from distutils.core import setup, Extension
540 setup(name="noddy", version="1.0",
542 Extension("noddy", ["noddy.c"]),
543 Extension("noddy2", ["noddy2.c"]),
547 Providing finer control over data attributes
548 --------------------------------------------
550 In this section, we'll provide finer control over how the :attr:`first` and
551 :attr:`last` attributes are set in the :class:`Noddy` example. In the previous
552 version of our module, the instance variables :attr:`first` and :attr:`last`
553 could be set to non-string values or even deleted. We want to make sure that
554 these attributes always contain strings.
556 .. literalinclude:: ../includes/noddy3.c
559 To provide greater control, over the :attr:`first` and :attr:`last` attributes,
560 we'll use custom getter and setter functions. Here are the functions for
561 getting and setting the :attr:`first` attribute::
563 Noddy_getfirst(Noddy *self, void *closure)
565 Py_INCREF(self->first);
570 Noddy_setfirst(Noddy *self, PyObject *value, void *closure)
573 PyErr_SetString(PyExc_TypeError, "Cannot delete the first attribute");
577 if (! PyString_Check(value)) {
578 PyErr_SetString(PyExc_TypeError,
579 "The first attribute value must be a string");
583 Py_DECREF(self->first);
590 The getter function is passed a :class:`Noddy` object and a "closure", which is
591 void pointer. In this case, the closure is ignored. (The closure supports an
592 advanced usage in which definition data is passed to the getter and setter. This
593 could, for example, be used to allow a single set of getter and setter functions
594 that decide the attribute to get or set based on data in the closure.)
596 The setter function is passed the :class:`Noddy` object, the new value, and the
597 closure. The new value may be *NULL*, in which case the attribute is being
598 deleted. In our setter, we raise an error if the attribute is deleted or if the
599 attribute value is not a string.
601 We create an array of :ctype:`PyGetSetDef` structures::
603 static PyGetSetDef Noddy_getseters[] = {
605 (getter)Noddy_getfirst, (setter)Noddy_setfirst,
609 (getter)Noddy_getlast, (setter)Noddy_setlast,
612 {NULL} /* Sentinel */
615 and register it in the :attr:`tp_getset` slot::
617 Noddy_getseters, /* tp_getset */
619 to register our attribute getters and setters.
621 The last item in a :ctype:`PyGetSetDef` structure is the closure mentioned
622 above. In this case, we aren't using the closure, so we just pass *NULL*.
624 We also remove the member definitions for these attributes::
626 static PyMemberDef Noddy_members[] = {
627 {"number", T_INT, offsetof(Noddy, number), 0,
629 {NULL} /* Sentinel */
632 We also need to update the :attr:`tp_init` handler to only allow strings [#]_ to
636 Noddy_init(Noddy *self, PyObject *args, PyObject *kwds)
638 PyObject *first=NULL, *last=NULL, *tmp;
640 static char *kwlist[] = {"first", "last", "number", NULL};
642 if (! PyArg_ParseTupleAndKeywords(args, kwds, "|SSi", kwlist,
664 With these changes, we can assure that the :attr:`first` and :attr:`last`
665 members are never *NULL* so we can remove checks for *NULL* values in almost all
666 cases. This means that most of the :cfunc:`Py_XDECREF` calls can be converted to
667 :cfunc:`Py_DECREF` calls. The only place we can't change these calls is in the
668 deallocator, where there is the possibility that the initialization of these
669 members failed in the constructor.
671 We also rename the module initialization function and module name in the
672 initialization function, as we did before, and we add an extra definition to the
673 :file:`setup.py` file.
676 Supporting cyclic garbage collection
677 ------------------------------------
679 Python has a cyclic-garbage collector that can identify unneeded objects even
680 when their reference counts are not zero. This can happen when objects are
681 involved in cycles. For example, consider::
687 In this example, we create a list that contains itself. When we delete it, it
688 still has a reference from itself. Its reference count doesn't drop to zero.
689 Fortunately, Python's cyclic-garbage collector will eventually figure out that
690 the list is garbage and free it.
692 In the second version of the :class:`Noddy` example, we allowed any kind of
693 object to be stored in the :attr:`first` or :attr:`last` attributes. [#]_ This
694 means that :class:`Noddy` objects can participate in cycles::
697 >>> n = noddy2.Noddy()
701 This is pretty silly, but it gives us an excuse to add support for the
702 cyclic-garbage collector to the :class:`Noddy` example. To support cyclic
703 garbage collection, types need to fill two slots and set a class flag that
706 .. literalinclude:: ../includes/noddy4.c
709 The traversal method provides access to subobjects that could participate in
713 Noddy_traverse(Noddy *self, visitproc visit, void *arg)
718 vret = visit(self->first, arg);
723 vret = visit(self->last, arg);
731 For each subobject that can participate in cycles, we need to call the
732 :cfunc:`visit` function, which is passed to the traversal method. The
733 :cfunc:`visit` function takes as arguments the subobject and the extra argument
734 *arg* passed to the traversal method. It returns an integer value that must be
735 returned if it is non-zero.
737 Python 2.4 and higher provide a :cfunc:`Py_VISIT` macro that automates calling
738 visit functions. With :cfunc:`Py_VISIT`, :cfunc:`Noddy_traverse` can be
742 Noddy_traverse(Noddy *self, visitproc visit, void *arg)
744 Py_VISIT(self->first);
745 Py_VISIT(self->last);
751 Note that the :attr:`tp_traverse` implementation must name its arguments exactly
752 *visit* and *arg* in order to use :cfunc:`Py_VISIT`. This is to encourage
753 uniformity across these boring implementations.
755 We also need to provide a method for clearing any subobjects that can
756 participate in cycles. We implement the method and reimplement the deallocator
760 Noddy_clear(Noddy *self)
776 Noddy_dealloc(Noddy* self)
779 self->ob_type->tp_free((PyObject*)self);
782 Notice the use of a temporary variable in :cfunc:`Noddy_clear`. We use the
783 temporary variable so that we can set each member to *NULL* before decrementing
784 its reference count. We do this because, as was discussed earlier, if the
785 reference count drops to zero, we might cause code to run that calls back into
786 the object. In addition, because we now support garbage collection, we also
787 have to worry about code being run that triggers garbage collection. If garbage
788 collection is run, our :attr:`tp_traverse` handler could get called. We can't
789 take a chance of having :cfunc:`Noddy_traverse` called when a member's reference
790 count has dropped to zero and its value hasn't been set to *NULL*.
792 Python 2.4 and higher provide a :cfunc:`Py_CLEAR` that automates the careful
793 decrementing of reference counts. With :cfunc:`Py_CLEAR`, the
794 :cfunc:`Noddy_clear` function can be simplified::
797 Noddy_clear(Noddy *self)
799 Py_CLEAR(self->first);
800 Py_CLEAR(self->last);
804 Finally, we add the :const:`Py_TPFLAGS_HAVE_GC` flag to the class flags::
806 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
808 That's pretty much it. If we had written custom :attr:`tp_alloc` or
809 :attr:`tp_free` slots, we'd need to modify them for cyclic-garbage collection.
810 Most extensions will use the versions automatically provided.
813 Subclassing other types
814 -----------------------
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.
821 In this example we will create a :class:`Shoddy` type that inherits from the
822 built-in :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. ::
827 >>> s = shoddy.Shoddy(range(3))
831 >>> print s.increment()
833 >>> print s.increment()
836 .. literalinclude:: ../includes/shoddy.c
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. ::
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.
851 When a Python object is a :class:`Shoddy` instance, its *PyObject\** pointer can
852 be safely cast to both *PyListObject\** and *Shoddy\**. ::
855 Shoddy_init(Shoddy *self, PyObject *args, PyObject *kwds)
857 if (PyList_Type.tp_init((PyObject *)self, args, kwds) < 0)
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.
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`.
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. ::
881 ShoddyType.tp_base = &PyList_Type;
882 if (PyType_Ready(&ShoddyType) < 0)
885 m = Py_InitModule3("shoddy", NULL, "Shoddy module");
889 Py_INCREF(&ShoddyType);
890 PyModule_AddObject(m, "Shoddy", (PyObject *) &ShoddyType);
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.
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.
902 .. _dnt-type-methods:
907 This section aims to give a quick fly-by on the various type methods you can
908 implement and what they do.
910 Here is the definition of :ctype:`PyTypeObject`, with some fields only used in
911 debug builds omitted:
913 .. literalinclude:: ../includes/typestruct.h
916 Now that's a *lot* of methods. Don't worry too much though - if you have a type
917 you want to define, the chances are very good that you will only implement a
920 As you probably expect by now, we're going to go over this and give more
921 information about the various handlers. We won't go in the order they are
922 defined in the structure, because there is a lot of historical baggage that
923 impacts the ordering of the fields; be sure your type initialization keeps the
924 fields in the right order! It's often easiest to find an example that includes
925 all the fields you need (even if they're initialized to ``0``) and then change
926 the values to suit your new type. ::
928 char *tp_name; /* For printing */
930 The name of the type - as mentioned in the last section, this will appear in
931 various places, almost entirely for diagnostic purposes. Try to choose something
932 that will be helpful in such a situation! ::
934 int tp_basicsize, tp_itemsize; /* For allocation */
936 These fields tell the runtime how much memory to allocate when new objects of
937 this type are created. Python has some built-in support for variable length
938 structures (think: strings, lists) which is where the :attr:`tp_itemsize` field
939 comes in. This will be dealt with later. ::
943 Here you can put a string (or its address) that you want returned when the
944 Python script references ``obj.__doc__`` to retrieve the doc string.
946 Now we come to the basic type methods---the ones most extension types will
950 Finalization and De-allocation
951 ------------------------------
954 single: object; deallocation
955 single: deallocation, object
956 single: object; finalization
957 single: finalization, of objects
961 destructor tp_dealloc;
963 This function is called when the reference count of the instance of your type is
964 reduced to zero and the Python interpreter wants to reclaim it. If your type
965 has memory to free or other clean-up to perform, put it here. The object itself
966 needs to be freed here as well. Here is an example of this function::
969 newdatatype_dealloc(newdatatypeobject * obj)
971 free(obj->obj_UnderlyingDatatypePtr);
972 obj->ob_type->tp_free(obj);
976 single: PyErr_Fetch()
977 single: PyErr_Restore()
979 One important requirement of the deallocator function is that it leaves any
980 pending exceptions alone. This is important since deallocators are frequently
981 called as the interpreter unwinds the Python stack; when the stack is unwound
982 due to an exception (rather than normal returns), nothing is done to protect the
983 deallocators from seeing that an exception has already been set. Any actions
984 which a deallocator performs which may cause additional Python code to be
985 executed may detect that an exception has been set. This can lead to misleading
986 errors from the interpreter. The proper way to protect against this is to save
987 a pending exception before performing the unsafe action, and restoring it when
988 done. This can be done using the :cfunc:`PyErr_Fetch` and
989 :cfunc:`PyErr_Restore` functions::
992 my_dealloc(PyObject *obj)
994 MyObject *self = (MyObject *) obj;
997 if (self->my_callback != NULL) {
998 PyObject *err_type, *err_value, *err_traceback;
999 int have_error = PyErr_Occurred() ? 1 : 0;
1002 PyErr_Fetch(&err_type, &err_value, &err_traceback);
1004 cbresult = PyObject_CallObject(self->my_callback, NULL);
1005 if (cbresult == NULL)
1006 PyErr_WriteUnraisable(self->my_callback);
1008 Py_DECREF(cbresult);
1011 PyErr_Restore(err_type, err_value, err_traceback);
1013 Py_DECREF(self->my_callback);
1015 obj->ob_type->tp_free((PyObject*)self);
1026 In Python, there are three ways to generate a textual representation of an
1027 object: the :func:`repr` function (or equivalent back-tick syntax), the
1028 :func:`str` function, and the :keyword:`print` statement. For most objects, the
1029 :keyword:`print` statement is equivalent to the :func:`str` function, but it is
1030 possible to special-case printing to a :ctype:`FILE\*` if necessary; this should
1031 only be done if efficiency is identified as a problem and profiling suggests
1032 that creating a temporary string object to be written to a file is too
1035 These handlers are all optional, and most types at most need to implement the
1036 :attr:`tp_str` and :attr:`tp_repr` handlers. ::
1042 The :attr:`tp_repr` handler should return a string object containing a
1043 representation of the instance for which it is called. Here is a simple
1047 newdatatype_repr(newdatatypeobject * obj)
1049 return PyString_FromFormat("Repr-ified_newdatatype{{size:\%d}}",
1050 obj->obj_UnderlyingDatatypePtr->size);
1053 If no :attr:`tp_repr` handler is specified, the interpreter will supply a
1054 representation that uses the type's :attr:`tp_name` and a uniquely-identifying
1055 value for the object.
1057 The :attr:`tp_str` handler is to :func:`str` what the :attr:`tp_repr` handler
1058 described above is to :func:`repr`; that is, it is called when Python code calls
1059 :func:`str` on an instance of your object. Its implementation is very similar
1060 to the :attr:`tp_repr` function, but the resulting string is intended for human
1061 consumption. If :attr:`tp_str` is not specified, the :attr:`tp_repr` handler is
1064 Here is a simple example::
1067 newdatatype_str(newdatatypeobject * obj)
1069 return PyString_FromFormat("Stringified_newdatatype{{size:\%d}}",
1070 obj->obj_UnderlyingDatatypePtr->size);
1073 The print function will be called whenever Python needs to "print" an instance
1074 of the type. For example, if 'node' is an instance of type TreeNode, then the
1075 print function is called when Python code calls::
1079 There is a flags argument and one flag, :const:`Py_PRINT_RAW`, and it suggests
1080 that you print without string quotes and possibly without interpreting escape
1083 The print function receives a file object as an argument. You will likely want
1084 to write to that file object.
1086 Here is a sample print function::
1089 newdatatype_print(newdatatypeobject *obj, FILE *fp, int flags)
1091 if (flags & Py_PRINT_RAW) {
1092 fprintf(fp, "<{newdatatype object--size: %d}>",
1093 obj->obj_UnderlyingDatatypePtr->size);
1096 fprintf(fp, "\"<{newdatatype object--size: %d}>\"",
1097 obj->obj_UnderlyingDatatypePtr->size);
1103 Attribute Management
1104 --------------------
1106 For every object which can support attributes, the corresponding type must
1107 provide the functions that control how the attributes are resolved. There needs
1108 to be a function which can retrieve attributes (if any are defined), and another
1109 to set attributes (if setting attributes is allowed). Removing an attribute is
1110 a special case, for which the new value passed to the handler is *NULL*.
1112 Python supports two pairs of attribute handlers; a type that supports attributes
1113 only needs to implement the functions for one pair. The difference is that one
1114 pair takes the name of the attribute as a :ctype:`char\*`, while the other
1115 accepts a :ctype:`PyObject\*`. Each type can use whichever pair makes more
1116 sense for the implementation's convenience. ::
1118 getattrfunc tp_getattr; /* char * version */
1119 setattrfunc tp_setattr;
1121 getattrofunc tp_getattrofunc; /* PyObject * version */
1122 setattrofunc tp_setattrofunc;
1124 If accessing attributes of an object is always a simple operation (this will be
1125 explained shortly), there are generic implementations which can be used to
1126 provide the :ctype:`PyObject\*` version of the attribute management functions.
1127 The actual need for type-specific attribute handlers almost completely
1128 disappeared starting with Python 2.2, though there are many examples which have
1129 not been updated to use some of the new generic mechanism that is available.
1132 Generic Attribute Management
1133 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1135 .. versionadded:: 2.2
1137 Most extension types only use *simple* attributes. So, what makes the
1138 attributes simple? There are only a couple of conditions that must be met:
1140 #. The name of the attributes must be known when :cfunc:`PyType_Ready` is
1143 #. No special processing is needed to record that an attribute was looked up or
1144 set, nor do actions need to be taken based on the value.
1146 Note that this list does not place any restrictions on the values of the
1147 attributes, when the values are computed, or how relevant data is stored.
1149 When :cfunc:`PyType_Ready` is called, it uses three tables referenced by the
1150 type object to create :term:`descriptor`\s which are placed in the dictionary of the
1151 type object. Each descriptor controls access to one attribute of the instance
1152 object. Each of the tables is optional; if all three are *NULL*, instances of
1153 the type will only have attributes that are inherited from their base type, and
1154 should leave the :attr:`tp_getattro` and :attr:`tp_setattro` fields *NULL* as
1155 well, allowing the base type to handle attributes.
1157 The tables are declared as three fields of the type object::
1159 struct PyMethodDef *tp_methods;
1160 struct PyMemberDef *tp_members;
1161 struct PyGetSetDef *tp_getset;
1163 If :attr:`tp_methods` is not *NULL*, it must refer to an array of
1164 :ctype:`PyMethodDef` structures. Each entry in the table is an instance of this
1167 typedef struct PyMethodDef {
1168 char *ml_name; /* method name */
1169 PyCFunction ml_meth; /* implementation function */
1170 int ml_flags; /* flags */
1171 char *ml_doc; /* docstring */
1174 One entry should be defined for each method provided by the type; no entries are
1175 needed for methods inherited from a base type. One additional entry is needed
1176 at the end; it is a sentinel that marks the end of the array. The
1177 :attr:`ml_name` field of the sentinel must be *NULL*.
1179 XXX Need to refer to some unified discussion of the structure fields, shared
1180 with the next section.
1182 The second table is used to define attributes which map directly to data stored
1183 in the instance. A variety of primitive C types are supported, and access may
1184 be read-only or read-write. The structures in the table are defined as::
1186 typedef struct PyMemberDef {
1194 For each entry in the table, a :term:`descriptor` will be constructed and added to the
1195 type which will be able to extract a value from the instance structure. The
1196 :attr:`type` field should contain one of the type codes defined in the
1197 :file:`structmember.h` header; the value will be used to determine how to
1198 convert Python values to and from C values. The :attr:`flags` field is used to
1199 store flags which control how the attribute can be accessed.
1201 XXX Need to move some of this to a shared section!
1203 The following flag constants are defined in :file:`structmember.h`; they may be
1204 combined using bitwise-OR.
1206 +---------------------------+----------------------------------------------+
1207 | Constant | Meaning |
1208 +===========================+==============================================+
1209 | :const:`READONLY` | Never writable. |
1210 +---------------------------+----------------------------------------------+
1211 | :const:`RO` | Shorthand for :const:`READONLY`. |
1212 +---------------------------+----------------------------------------------+
1213 | :const:`READ_RESTRICTED` | Not readable in restricted mode. |
1214 +---------------------------+----------------------------------------------+
1215 | :const:`WRITE_RESTRICTED` | Not writable in restricted mode. |
1216 +---------------------------+----------------------------------------------+
1217 | :const:`RESTRICTED` | Not readable or writable in restricted mode. |
1218 +---------------------------+----------------------------------------------+
1223 single: READ_RESTRICTED
1224 single: WRITE_RESTRICTED
1227 An interesting advantage of using the :attr:`tp_members` table to build
1228 descriptors that are used at runtime is that any attribute defined this way can
1229 have an associated doc string simply by providing the text in the table. An
1230 application can use the introspection API to retrieve the descriptor from the
1231 class object, and get the doc string using its :attr:`__doc__` attribute.
1233 As with the :attr:`tp_methods` table, a sentinel entry with a :attr:`name` value
1234 of *NULL* is required.
1236 .. XXX Descriptors need to be explained in more detail somewhere, but not here.
1238 Descriptor objects have two handler functions which correspond to the
1239 \member{tp_getattro} and \member{tp_setattro} handlers. The
1240 \method{__get__()} handler is a function which is passed the descriptor,
1241 instance, and type objects, and returns the value of the attribute, or it
1242 returns \NULL{} and sets an exception. The \method{__set__()} handler is
1243 passed the descriptor, instance, type, and new value;
1246 Type-specific Attribute Management
1247 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1249 For simplicity, only the :ctype:`char\*` version will be demonstrated here; the
1250 type of the name parameter is the only difference between the :ctype:`char\*`
1251 and :ctype:`PyObject\*` flavors of the interface. This example effectively does
1252 the same thing as the generic example above, but does not use the generic
1253 support added in Python 2.2. The value in showing this is two-fold: it
1254 demonstrates how basic attribute management can be done in a way that is
1255 portable to older versions of Python, and explains how the handler functions are
1256 called, so that if you do need to extend their functionality, you'll understand
1257 what needs to be done.
1259 The :attr:`tp_getattr` handler is called when the object requires an attribute
1260 look-up. It is called in the same situations where the :meth:`__getattr__`
1261 method of a class would be called.
1263 A likely way to handle this is (1) to implement a set of functions (such as
1264 :cfunc:`newdatatype_getSize` and :cfunc:`newdatatype_setSize` in the example
1265 below), (2) provide a method table listing these functions, and (3) provide a
1266 getattr function that returns the result of a lookup in that table. The method
1267 table uses the same structure as the :attr:`tp_methods` field of the type
1270 Here is an example::
1272 static PyMethodDef newdatatype_methods[] = {
1273 {"getSize", (PyCFunction)newdatatype_getSize, METH_VARARGS,
1274 "Return the current size."},
1275 {"setSize", (PyCFunction)newdatatype_setSize, METH_VARARGS,
1277 {NULL, NULL, 0, NULL} /* sentinel */
1281 newdatatype_getattr(newdatatypeobject *obj, char *name)
1283 return Py_FindMethod(newdatatype_methods, (PyObject *)obj, name);
1286 The :attr:`tp_setattr` handler is called when the :meth:`__setattr__` or
1287 :meth:`__delattr__` method of a class instance would be called. When an
1288 attribute should be deleted, the third parameter will be *NULL*. Here is an
1289 example that simply raises an exception; if this were really all you wanted, the
1290 :attr:`tp_setattr` handler should be set to *NULL*. ::
1293 newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
1295 (void)PyErr_Format(PyExc_RuntimeError, "Read-only attribute: \%s", name);
1307 The :attr:`tp_compare` handler is called when comparisons are needed and the
1308 object does not implement the specific rich comparison method which matches the
1309 requested comparison. (It is always used if defined and the
1310 :cfunc:`PyObject_Compare` or :cfunc:`PyObject_Cmp` functions are used, or if
1311 :func:`cmp` is used from Python.) It is analogous to the :meth:`__cmp__` method.
1312 This function should return ``-1`` if *obj1* is less than *obj2*, ``0`` if they
1313 are equal, and ``1`` if *obj1* is greater than *obj2*. (It was previously
1314 allowed to return arbitrary negative or positive integers for less than and
1315 greater than, respectively; as of Python 2.2, this is no longer allowed. In the
1316 future, other return values may be assigned a different meaning.)
1318 A :attr:`tp_compare` handler may raise an exception. In this case it should
1319 return a negative value. The caller has to test for the exception using
1320 :cfunc:`PyErr_Occurred`.
1322 Here is a sample implementation::
1325 newdatatype_compare(newdatatypeobject * obj1, newdatatypeobject * obj2)
1329 if (obj1->obj_UnderlyingDatatypePtr->size <
1330 obj2->obj_UnderlyingDatatypePtr->size) {
1333 else if (obj1->obj_UnderlyingDatatypePtr->size >
1334 obj2->obj_UnderlyingDatatypePtr->size) {
1344 Abstract Protocol Support
1345 -------------------------
1347 Python supports a variety of *abstract* 'protocols;' the specific interfaces
1348 provided to use these interfaces are documented in :ref:`abstract`.
1351 A number of these abstract interfaces were defined early in the development of
1352 the Python implementation. In particular, the number, mapping, and sequence
1353 protocols have been part of Python since the beginning. Other protocols have
1354 been added over time. For protocols which depend on several handler routines
1355 from the type implementation, the older protocols have been defined as optional
1356 blocks of handlers referenced by the type object. For newer protocols there are
1357 additional slots in the main type object, with a flag bit being set to indicate
1358 that the slots are present and should be checked by the interpreter. (The flag
1359 bit does not indicate that the slot values are non-*NULL*. The flag may be set
1360 to indicate the presence of a slot, but a slot may still be unfilled.) ::
1362 PyNumberMethods tp_as_number;
1363 PySequenceMethods tp_as_sequence;
1364 PyMappingMethods tp_as_mapping;
1366 If you wish your object to be able to act like a number, a sequence, or a
1367 mapping object, then you place the address of a structure that implements the C
1368 type :ctype:`PyNumberMethods`, :ctype:`PySequenceMethods`, or
1369 :ctype:`PyMappingMethods`, respectively. It is up to you to fill in this
1370 structure with appropriate values. You can find examples of the use of each of
1371 these in the :file:`Objects` directory of the Python source distribution. ::
1375 This function, if you choose to provide it, should return a hash number for an
1376 instance of your data type. Here is a moderately pointless example::
1379 newdatatype_hash(newdatatypeobject *obj)
1382 result = obj->obj_UnderlyingDatatypePtr->size;
1383 result = result * 3;
1389 ternaryfunc tp_call;
1391 This function is called when an instance of your data type is "called", for
1392 example, if ``obj1`` is an instance of your data type and the Python script
1393 contains ``obj1('hello')``, the :attr:`tp_call` handler is invoked.
1395 This function takes three arguments:
1397 #. *arg1* is the instance of the data type which is the subject of the call. If
1398 the call is ``obj1('hello')``, then *arg1* is ``obj1``.
1400 #. *arg2* is a tuple containing the arguments to the call. You can use
1401 :cfunc:`PyArg_ParseTuple` to extract the arguments.
1403 #. *arg3* is a dictionary of keyword arguments that were passed. If this is
1404 non-*NULL* and you support keyword arguments, use
1405 :cfunc:`PyArg_ParseTupleAndKeywords` to extract the arguments. If you do not
1406 want to support keyword arguments and this is non-*NULL*, raise a
1407 :exc:`TypeError` with a message saying that keyword arguments are not supported.
1409 Here is a desultory example of the implementation of the call function. ::
1411 /* Implement the call function.
1412 * obj1 is the instance receiving the call.
1413 * obj2 is a tuple containing the arguments to the call, in this
1417 newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *other)
1424 if (!PyArg_ParseTuple(args, "sss:call", &arg1, &arg2, &arg3)) {
1427 result = PyString_FromFormat(
1428 "Returning -- value: [\%d] arg1: [\%s] arg2: [\%s] arg3: [\%s]\n",
1429 obj->obj_UnderlyingDatatypePtr->size,
1431 printf("\%s", PyString_AS_STRING(result));
1435 XXX some fields need to be added here... ::
1437 /* Added in release 2.2 */
1439 getiterfunc tp_iter;
1440 iternextfunc tp_iternext;
1442 These functions provide support for the iterator protocol. Any object which
1443 wishes to support iteration over its contents (which may be generated during
1444 iteration) must implement the ``tp_iter`` handler. Objects which are returned
1445 by a ``tp_iter`` handler must implement both the ``tp_iter`` and ``tp_iternext``
1446 handlers. Both handlers take exactly one parameter, the instance for which they
1447 are being called, and return a new reference. In the case of an error, they
1448 should set an exception and return *NULL*.
1450 For an object which represents an iterable collection, the ``tp_iter`` handler
1451 must return an iterator object. The iterator object is responsible for
1452 maintaining the state of the iteration. For collections which can support
1453 multiple iterators which do not interfere with each other (as lists and tuples
1454 do), a new iterator should be created and returned. Objects which can only be
1455 iterated over once (usually due to side effects of iteration) should implement
1456 this handler by returning a new reference to themselves, and should also
1457 implement the ``tp_iternext`` handler. File objects are an example of such an
1460 Iterator objects should implement both handlers. The ``tp_iter`` handler should
1461 return a new reference to the iterator (this is the same as the ``tp_iter``
1462 handler for objects which can only be iterated over destructively). The
1463 ``tp_iternext`` handler should return a new reference to the next object in the
1464 iteration if there is one. If the iteration has reached the end, it may return
1465 *NULL* without setting an exception or it may set :exc:`StopIteration`; avoiding
1466 the exception can yield slightly better performance. If an actual error occurs,
1467 it should set an exception and return *NULL*.
1470 .. _weakref-support:
1472 Weak Reference Support
1473 ----------------------
1475 One of the goals of Python's weak-reference implementation is to allow any type
1476 to participate in the weak reference mechanism without incurring the overhead on
1477 those objects which do not benefit by weak referencing (such as numbers).
1479 For an object to be weakly referencable, the extension must include a
1480 :ctype:`PyObject\*` field in the instance structure for the use of the weak
1481 reference mechanism; it must be initialized to *NULL* by the object's
1482 constructor. It must also set the :attr:`tp_weaklistoffset` field of the
1483 corresponding type object to the offset of the field. For example, the instance
1484 type is defined with the following structure::
1488 PyClassObject *in_class; /* The class object */
1489 PyObject *in_dict; /* A dictionary */
1490 PyObject *in_weakreflist; /* List of weak references */
1493 The statically-declared type object for instances is defined this way::
1495 PyTypeObject PyInstance_Type = {
1496 PyObject_HEAD_INIT(&PyType_Type)
1500 /* Lots of stuff omitted for brevity... */
1502 Py_TPFLAGS_DEFAULT, /* tp_flags */
1504 0, /* tp_traverse */
1506 0, /* tp_richcompare */
1507 offsetof(PyInstanceObject, in_weakreflist), /* tp_weaklistoffset */
1510 The type constructor is responsible for initializing the weak reference list to
1515 /* Other initialization stuff omitted for brevity */
1517 self->in_weakreflist = NULL;
1519 return (PyObject *) self;
1522 The only further addition is that the destructor needs to call the weak
1523 reference manager to clear any weak references. This should be done before any
1524 other parts of the destruction have occurred, but is only required if the weak
1525 reference list is non-*NULL*::
1528 instance_dealloc(PyInstanceObject *inst)
1530 /* Allocate temporaries if needed, but do not begin
1531 destruction just yet.
1534 if (inst->in_weakreflist != NULL)
1535 PyObject_ClearWeakRefs((PyObject *) inst);
1537 /* Proceed with object destruction normally. */
1544 Remember that you can omit most of these functions, in which case you provide
1545 ``0`` as a value. There are type definitions for each of the functions you must
1546 provide. They are in :file:`object.h` in the Python include directory that
1547 comes with the source distribution of Python.
1549 In order to learn how to implement any specific method for your new data type,
1550 do the following: Download and unpack the Python source distribution. Go the
1551 :file:`Objects` directory, then search the C source files for ``tp_`` plus the
1552 function you want (for example, ``tp_print`` or ``tp_compare``). You will find
1553 examples of the function you want to implement.
1555 When you need to verify that an object is an instance of the type you are
1556 implementing, use the :cfunc:`PyObject_TypeCheck` function. A sample of its use
1557 might be something like the following::
1559 if (! PyObject_TypeCheck(some_object, &MyType)) {
1560 PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
1564 .. rubric:: Footnotes
1566 .. [#] This is true when we know that the object is a basic type, like a string or a
1569 .. [#] We relied on this in the :attr:`tp_dealloc` handler in this example, because our
1570 type doesn't support garbage collection. Even if a type supports garbage
1571 collection, there are calls that can be made to "untrack" the object from
1572 garbage collection, however, these calls are advanced and not covered here.
1574 .. [#] We now know that the first and last members are strings, so perhaps we could be
1575 less careful about decrementing their reference counts, however, we accept
1576 instances of string subclasses. Even though deallocating normal strings won't
1577 call back into our objects, we can't guarantee that deallocating an instance of
1578 a string subclass won't call back into our objects.
1580 .. [#] Even in the third version, we aren't guaranteed to avoid cycles. Instances of
1581 string subclasses are allowed and string subclasses could allow cycles even if
1582 normal strings don't.