summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/extending%2Fnewtypes.html
diff options
context:
space:
mode:
Diffstat (limited to 'devdocs/python~3.12/extending%2Fnewtypes.html')
-rw-r--r--devdocs/python~3.12/extending%2Fnewtypes.html281
1 files changed, 281 insertions, 0 deletions
diff --git a/devdocs/python~3.12/extending%2Fnewtypes.html b/devdocs/python~3.12/extending%2Fnewtypes.html
new file mode 100644
index 00000000..f8d2c6cd
--- /dev/null
+++ b/devdocs/python~3.12/extending%2Fnewtypes.html
@@ -0,0 +1,281 @@
+ <span id="new-types-topics"></span><h1> Defining Extension Types: Assorted Topics</h1> <p id="dnt-type-methods">This section aims to give a quick fly-by on the various type methods you can implement and what they do.</p> <p>Here is the definition of <a class="reference internal" href="../c-api/type#c.PyTypeObject" title="PyTypeObject"><code>PyTypeObject</code></a>, with some fields only used in <a class="reference internal" href="../using/configure#debug-build"><span class="std std-ref">debug builds</span></a> omitted:</p> <pre data-language="c">typedef struct _typeobject {
+ PyObject_VAR_HEAD
+ const char *tp_name; /* For printing, in format "&lt;module&gt;.&lt;name&gt;" */
+ Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
+
+ /* Methods to implement standard operations */
+
+ destructor tp_dealloc;
+ Py_ssize_t tp_vectorcall_offset;
+ getattrfunc tp_getattr;
+ setattrfunc tp_setattr;
+ PyAsyncMethods *tp_as_async; /* formerly known as tp_compare (Python 2)
+ or tp_reserved (Python 3) */
+ reprfunc tp_repr;
+
+ /* Method suites for standard classes */
+
+ PyNumberMethods *tp_as_number;
+ PySequenceMethods *tp_as_sequence;
+ PyMappingMethods *tp_as_mapping;
+
+ /* More standard operations (here for binary compatibility) */
+
+ hashfunc tp_hash;
+ ternaryfunc tp_call;
+ reprfunc tp_str;
+ getattrofunc tp_getattro;
+ setattrofunc tp_setattro;
+
+ /* Functions to access object as input/output buffer */
+ PyBufferProcs *tp_as_buffer;
+
+ /* Flags to define presence of optional/expanded features */
+ unsigned long tp_flags;
+
+ const char *tp_doc; /* Documentation string */
+
+ /* Assigned meaning in release 2.0 */
+ /* call function for all accessible objects */
+ traverseproc tp_traverse;
+
+ /* delete references to contained objects */
+ inquiry tp_clear;
+
+ /* Assigned meaning in release 2.1 */
+ /* rich comparisons */
+ richcmpfunc tp_richcompare;
+
+ /* weak reference enabler */
+ Py_ssize_t tp_weaklistoffset;
+
+ /* Iterators */
+ getiterfunc tp_iter;
+ iternextfunc tp_iternext;
+
+ /* Attribute descriptor and subclassing stuff */
+ struct PyMethodDef *tp_methods;
+ struct PyMemberDef *tp_members;
+ struct PyGetSetDef *tp_getset;
+ // Strong reference on a heap type, borrowed reference on a static type
+ struct _typeobject *tp_base;
+ PyObject *tp_dict;
+ descrgetfunc tp_descr_get;
+ descrsetfunc tp_descr_set;
+ Py_ssize_t tp_dictoffset;
+ initproc tp_init;
+ allocfunc tp_alloc;
+ newfunc tp_new;
+ freefunc tp_free; /* Low-level free-memory routine */
+ inquiry tp_is_gc; /* For PyObject_IS_GC */
+ PyObject *tp_bases;
+ PyObject *tp_mro; /* method resolution order */
+ PyObject *tp_cache;
+ PyObject *tp_subclasses;
+ PyObject *tp_weaklist;
+ destructor tp_del;
+
+ /* Type attribute cache version tag. Added in version 2.6 */
+ unsigned int tp_version_tag;
+
+ destructor tp_finalize;
+ vectorcallfunc tp_vectorcall;
+
+ /* bitset of which type-watchers care about this type */
+ unsigned char tp_watched;
+} PyTypeObject;
+</pre> <p>Now that’s a <em>lot</em> of methods. Don’t worry too much though – if you have a type you want to define, the chances are very good that you will only implement a handful of these.</p> <p>As you probably expect by now, we’re going to go over this and give more information about the various handlers. We won’t go in the order they are defined in the structure, because there is a lot of historical baggage that impacts the ordering of the fields. It’s often easiest to find an example that includes the fields you need and then change the values to suit your new type.</p> <pre data-language="c">const char *tp_name; /* For printing */
+</pre> <p>The name of the type – as mentioned in the previous chapter, this will appear in various places, almost entirely for diagnostic purposes. Try to choose something that will be helpful in such a situation!</p> <pre data-language="c">Py_ssize_t tp_basicsize, tp_itemsize; /* For allocation */
+</pre> <p>These fields tell the runtime how much memory to allocate when new objects of this type are created. Python has some built-in support for variable length structures (think: strings, tuples) which is where the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_itemsize" title="PyTypeObject.tp_itemsize"><code>tp_itemsize</code></a> field comes in. This will be dealt with later.</p> <pre data-language="c">const char *tp_doc;
+</pre> <p>Here you can put a string (or its address) that you want returned when the Python script references <code>obj.__doc__</code> to retrieve the doc string.</p> <p>Now we come to the basic type methods – the ones most extension types will implement.</p> <section id="finalization-and-de-allocation"> <h2>
+<span class="section-number">3.1. </span>Finalization and De-allocation</h2> <pre data-language="c">destructor tp_dealloc;
+</pre> <p>This function is called when the reference count of the instance of your type is reduced to zero and the Python interpreter wants to reclaim it. If your type has memory to free or other clean-up to perform, you can put it here. The object itself needs to be freed here as well. Here is an example of this function:</p> <pre data-language="c">static void
+newdatatype_dealloc(newdatatypeobject *obj)
+{
+ free(obj-&gt;obj_UnderlyingDatatypePtr);
+ Py_TYPE(obj)-&gt;tp_free((PyObject *)obj);
+}
+</pre> <p>If your type supports garbage collection, the destructor should call <a class="reference internal" href="../c-api/gcsupport#c.PyObject_GC_UnTrack" title="PyObject_GC_UnTrack"><code>PyObject_GC_UnTrack()</code></a> before clearing any member fields:</p> <pre data-language="c">static void
+newdatatype_dealloc(newdatatypeobject *obj)
+{
+ PyObject_GC_UnTrack(obj);
+ Py_CLEAR(obj-&gt;other_obj);
+ ...
+ Py_TYPE(obj)-&gt;tp_free((PyObject *)obj);
+}
+</pre> <p id="index-1">One important requirement of the deallocator function is that it leaves any pending exceptions alone. This is important since deallocators are frequently called as the interpreter unwinds the Python stack; when the stack is unwound due to an exception (rather than normal returns), nothing is done to protect the deallocators from seeing that an exception has already been set. Any actions which a deallocator performs which may cause additional Python code to be executed may detect that an exception has been set. This can lead to misleading errors from the interpreter. The proper way to protect against this is to save a pending exception before performing the unsafe action, and restoring it when done. This can be done using the <a class="reference internal" href="../c-api/exceptions#c.PyErr_Fetch" title="PyErr_Fetch"><code>PyErr_Fetch()</code></a> and <a class="reference internal" href="../c-api/exceptions#c.PyErr_Restore" title="PyErr_Restore"><code>PyErr_Restore()</code></a> functions:</p> <pre data-language="c">static void
+my_dealloc(PyObject *obj)
+{
+ MyObject *self = (MyObject *) obj;
+ PyObject *cbresult;
+
+ if (self-&gt;my_callback != NULL) {
+ PyObject *err_type, *err_value, *err_traceback;
+
+ /* This saves the current exception state */
+ PyErr_Fetch(&amp;err_type, &amp;err_value, &amp;err_traceback);
+
+ cbresult = PyObject_CallNoArgs(self-&gt;my_callback);
+ if (cbresult == NULL)
+ PyErr_WriteUnraisable(self-&gt;my_callback);
+ else
+ Py_DECREF(cbresult);
+
+ /* This restores the saved exception state */
+ PyErr_Restore(err_type, err_value, err_traceback);
+
+ Py_DECREF(self-&gt;my_callback);
+ }
+ Py_TYPE(obj)-&gt;tp_free((PyObject*)self);
+}
+</pre> <div class="admonition note"> <p class="admonition-title">Note</p> <p>There are limitations to what you can safely do in a deallocator function. First, if your type supports garbage collection (using <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_traverse" title="PyTypeObject.tp_traverse"><code>tp_traverse</code></a> and/or <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_clear" title="PyTypeObject.tp_clear"><code>tp_clear</code></a>), some of the object’s members can have been cleared or finalized by the time <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code>tp_dealloc</code></a> is called. Second, in <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code>tp_dealloc</code></a>, your object is in an unstable state: its reference count is equal to zero. Any call to a non-trivial object or API (as in the example above) might end up calling <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code>tp_dealloc</code></a> again, causing a double free and a crash.</p> <p>Starting with Python 3.4, it is recommended not to put any complex finalization code in <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_dealloc" title="PyTypeObject.tp_dealloc"><code>tp_dealloc</code></a>, and instead use the new <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_finalize" title="PyTypeObject.tp_finalize"><code>tp_finalize</code></a> type method.</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p><span class="target" id="index-2"></span><a class="pep reference external" href="https://peps.python.org/pep-0442/"><strong>PEP 442</strong></a> explains the new finalization scheme.</p> </div> </div> </section> <section id="object-presentation"> <span id="index-3"></span><h2>
+<span class="section-number">3.2. </span>Object Presentation</h2> <p>In Python, there are two ways to generate a textual representation of an object: the <a class="reference internal" href="../library/functions#repr" title="repr"><code>repr()</code></a> function, and the <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str()</code></a> function. (The <a class="reference internal" href="../library/functions#print" title="print"><code>print()</code></a> function just calls <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str()</code></a>.) These handlers are both optional.</p> <pre data-language="c">reprfunc tp_repr;
+reprfunc tp_str;
+</pre> <p>The <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code>tp_repr</code></a> handler should return a string object containing a representation of the instance for which it is called. Here is a simple example:</p> <pre data-language="c">static PyObject *
+newdatatype_repr(newdatatypeobject *obj)
+{
+ return PyUnicode_FromFormat("Repr-ified_newdatatype{{size:%d}}",
+ obj-&gt;obj_UnderlyingDatatypePtr-&gt;size);
+}
+</pre> <p>If no <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code>tp_repr</code></a> handler is specified, the interpreter will supply a representation that uses the type’s <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_name" title="PyTypeObject.tp_name"><code>tp_name</code></a> and a uniquely identifying value for the object.</p> <p>The <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code>tp_str</code></a> handler is to <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str()</code></a> what the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code>tp_repr</code></a> handler described above is to <a class="reference internal" href="../library/functions#repr" title="repr"><code>repr()</code></a>; that is, it is called when Python code calls <a class="reference internal" href="../library/stdtypes#str" title="str"><code>str()</code></a> on an instance of your object. Its implementation is very similar to the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code>tp_repr</code></a> function, but the resulting string is intended for human consumption. If <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_str" title="PyTypeObject.tp_str"><code>tp_str</code></a> is not specified, the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_repr" title="PyTypeObject.tp_repr"><code>tp_repr</code></a> handler is used instead.</p> <p>Here is a simple example:</p> <pre data-language="c">static PyObject *
+newdatatype_str(newdatatypeobject *obj)
+{
+ return PyUnicode_FromFormat("Stringified_newdatatype{{size:%d}}",
+ obj-&gt;obj_UnderlyingDatatypePtr-&gt;size);
+}
+</pre> </section> <section id="attribute-management"> <h2>
+<span class="section-number">3.3. </span>Attribute Management</h2> <p>For every object which can support attributes, the corresponding type must provide the functions that control how the attributes are resolved. There needs to be a function which can retrieve attributes (if any are defined), and another to set attributes (if setting attributes is allowed). Removing an attribute is a special case, for which the new value passed to the handler is <code>NULL</code>.</p> <p>Python supports two pairs of attribute handlers; a type that supports attributes only needs to implement the functions for one pair. The difference is that one pair takes the name of the attribute as a <span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">*</span></span>, while the other accepts a <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span>. Each type can use whichever pair makes more sense for the implementation’s convenience.</p> <pre data-language="c">getattrfunc tp_getattr; /* char * version */
+setattrfunc tp_setattr;
+/* ... */
+getattrofunc tp_getattro; /* PyObject * version */
+setattrofunc tp_setattro;
+</pre> <p>If accessing attributes of an object is always a simple operation (this will be explained shortly), there are generic implementations which can be used to provide the <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span> version of the attribute management functions. The actual need for type-specific attribute handlers almost completely disappeared starting with Python 2.2, though there are many examples which have not been updated to use some of the new generic mechanism that is available.</p> <section id="generic-attribute-management"> <span id="id1"></span><h3>
+<span class="section-number">3.3.1. </span>Generic Attribute Management</h3> <p>Most extension types only use <em>simple</em> attributes. So, what makes the attributes simple? There are only a couple of conditions that must be met:</p> <ol class="arabic simple"> <li>The name of the attributes must be known when <a class="reference internal" href="../c-api/type#c.PyType_Ready" title="PyType_Ready"><code>PyType_Ready()</code></a> is called.</li> <li>No special processing is needed to record that an attribute was looked up or set, nor do actions need to be taken based on the value.</li> </ol> <p>Note that this list does not place any restrictions on the values of the attributes, when the values are computed, or how relevant data is stored.</p> <p>When <a class="reference internal" href="../c-api/type#c.PyType_Ready" title="PyType_Ready"><code>PyType_Ready()</code></a> is called, it uses three tables referenced by the type object to create <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptor</span></a>s which are placed in the dictionary of the type object. Each descriptor controls access to one attribute of the instance object. Each of the tables is optional; if all three are <code>NULL</code>, instances of the type will only have attributes that are inherited from their base type, and should leave the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_getattro" title="PyTypeObject.tp_getattro"><code>tp_getattro</code></a> and <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_setattro" title="PyTypeObject.tp_setattro"><code>tp_setattro</code></a> fields <code>NULL</code> as well, allowing the base type to handle attributes.</p> <p>The tables are declared as three fields of the type object:</p> <pre data-language="c">struct PyMethodDef *tp_methods;
+struct PyMemberDef *tp_members;
+struct PyGetSetDef *tp_getset;
+</pre> <p>If <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code>tp_methods</code></a> is not <code>NULL</code>, it must refer to an array of <a class="reference internal" href="../c-api/structures#c.PyMethodDef" title="PyMethodDef"><code>PyMethodDef</code></a> structures. Each entry in the table is an instance of this structure:</p> <pre data-language="c">typedef struct PyMethodDef {
+ const char *ml_name; /* method name */
+ PyCFunction ml_meth; /* implementation function */
+ int ml_flags; /* flags */
+ const char *ml_doc; /* docstring */
+} PyMethodDef;
+</pre> <p>One entry should be defined for each method provided by the type; no entries are needed for methods inherited from a base type. One additional entry is needed at the end; it is a sentinel that marks the end of the array. The <a class="reference internal" href="../c-api/structures#c.PyMethodDef.ml_name" title="PyMethodDef.ml_name"><code>ml_name</code></a> field of the sentinel must be <code>NULL</code>.</p> <p>The second table is used to define attributes which map directly to data stored in the instance. A variety of primitive C types are supported, and access may be read-only or read-write. The structures in the table are defined as:</p> <pre data-language="c">typedef struct PyMemberDef {
+ const char *name;
+ int type;
+ int offset;
+ int flags;
+ const char *doc;
+} PyMemberDef;
+</pre> <p>For each entry in the table, a <a class="reference internal" href="../glossary#term-descriptor"><span class="xref std std-term">descriptor</span></a> will be constructed and added to the type which will be able to extract a value from the instance structure. The <a class="reference internal" href="../c-api/structures#c.PyMemberDef.type" title="PyMemberDef.type"><code>type</code></a> field should contain a type code like <a class="reference internal" href="../c-api/structures#c.Py_T_INT" title="Py_T_INT"><code>Py_T_INT</code></a> or <a class="reference internal" href="../c-api/structures#c.Py_T_DOUBLE" title="Py_T_DOUBLE"><code>Py_T_DOUBLE</code></a>; the value will be used to determine how to convert Python values to and from C values. The <a class="reference internal" href="../c-api/structures#c.PyMemberDef.flags" title="PyMemberDef.flags"><code>flags</code></a> field is used to store flags which control how the attribute can be accessed: you can set it to <a class="reference internal" href="../c-api/structures#c.Py_READONLY" title="Py_READONLY"><code>Py_READONLY</code></a> to prevent Python code from setting it.</p> <p>An interesting advantage of using the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_members" title="PyTypeObject.tp_members"><code>tp_members</code></a> table to build descriptors that are used at runtime is that any attribute defined this way can have an associated doc string simply by providing the text in the table. An application can use the introspection API to retrieve the descriptor from the class object, and get the doc string using its <code>__doc__</code> attribute.</p> <p>As with the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_methods" title="PyTypeObject.tp_methods"><code>tp_methods</code></a> table, a sentinel entry with a <a class="reference internal" href="../c-api/structures#c.PyMethodDef.ml_name" title="PyMethodDef.ml_name"><code>ml_name</code></a> value of <code>NULL</code> is required.</p> </section> <section id="type-specific-attribute-management"> <h3>
+<span class="section-number">3.3.2. </span>Type-specific Attribute Management</h3> <p>For simplicity, only the <span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">*</span></span> version will be demonstrated here; the type of the name parameter is the only difference between the <span class="c-expr sig sig-inline c"><span class="kt">char</span><span class="p">*</span></span> and <span class="c-expr sig sig-inline c"><a class="reference internal" href="../c-api/structures#c.PyObject" title="PyObject"><span class="n">PyObject</span></a><span class="p">*</span></span> flavors of the interface. This example effectively does the same thing as the generic example above, but does not use the generic support added in Python 2.2. It explains how the handler functions are called, so that if you do need to extend their functionality, you’ll understand what needs to be done.</p> <p>The <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_getattr" title="PyTypeObject.tp_getattr"><code>tp_getattr</code></a> handler is called when the object requires an attribute look-up. It is called in the same situations where the <a class="reference internal" href="../reference/datamodel#object.__getattr__" title="object.__getattr__"><code>__getattr__()</code></a> method of a class would be called.</p> <p>Here is an example:</p> <pre data-language="c">static PyObject *
+newdatatype_getattr(newdatatypeobject *obj, char *name)
+{
+ if (strcmp(name, "data") == 0)
+ {
+ return PyLong_FromLong(obj-&gt;data);
+ }
+
+ PyErr_Format(PyExc_AttributeError,
+ "'%.100s' object has no attribute '%.400s'",
+ Py_TYPE(obj)-&gt;tp_name, name);
+ return NULL;
+}
+</pre> <p>The <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code>tp_setattr</code></a> handler is called when the <a class="reference internal" href="../reference/datamodel#object.__setattr__" title="object.__setattr__"><code>__setattr__()</code></a> or <a class="reference internal" href="../reference/datamodel#object.__delattr__" title="object.__delattr__"><code>__delattr__()</code></a> method of a class instance would be called. When an attribute should be deleted, the third parameter will be <code>NULL</code>. Here is an example that simply raises an exception; if this were really all you wanted, the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_setattr" title="PyTypeObject.tp_setattr"><code>tp_setattr</code></a> handler should be set to <code>NULL</code>.</p> <pre data-language="c">static int
+newdatatype_setattr(newdatatypeobject *obj, char *name, PyObject *v)
+{
+ PyErr_Format(PyExc_RuntimeError, "Read-only attribute: %s", name);
+ return -1;
+}
+</pre> </section> </section> <section id="object-comparison"> <h2>
+<span class="section-number">3.4. </span>Object Comparison</h2> <pre data-language="c">richcmpfunc tp_richcompare;
+</pre> <p>The <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_richcompare" title="PyTypeObject.tp_richcompare"><code>tp_richcompare</code></a> handler is called when comparisons are needed. It is analogous to the <a class="reference internal" href="../reference/datamodel#richcmpfuncs"><span class="std std-ref">rich comparison methods</span></a>, like <code>__lt__()</code>, and also called by <a class="reference internal" href="../c-api/object#c.PyObject_RichCompare" title="PyObject_RichCompare"><code>PyObject_RichCompare()</code></a> and <a class="reference internal" href="../c-api/object#c.PyObject_RichCompareBool" title="PyObject_RichCompareBool"><code>PyObject_RichCompareBool()</code></a>.</p> <p>This function is called with two Python objects and the operator as arguments, where the operator is one of <code>Py_EQ</code>, <code>Py_NE</code>, <code>Py_LE</code>, <code>Py_GE</code>, <code>Py_LT</code> or <code>Py_GT</code>. It should compare the two objects with respect to the specified operator and return <code>Py_True</code> or <code>Py_False</code> if the comparison is successful, <code>Py_NotImplemented</code> to indicate that comparison is not implemented and the other object’s comparison method should be tried, or <code>NULL</code> if an exception was set.</p> <p>Here is a sample implementation, for a datatype that is considered equal if the size of an internal pointer is equal:</p> <pre data-language="c">static PyObject *
+newdatatype_richcmp(newdatatypeobject *obj1, newdatatypeobject *obj2, int op)
+{
+ PyObject *result;
+ int c, size1, size2;
+
+ /* code to make sure that both arguments are of type
+ newdatatype omitted */
+
+ size1 = obj1-&gt;obj_UnderlyingDatatypePtr-&gt;size;
+ size2 = obj2-&gt;obj_UnderlyingDatatypePtr-&gt;size;
+
+ switch (op) {
+ case Py_LT: c = size1 &lt; size2; break;
+ case Py_LE: c = size1 &lt;= size2; break;
+ case Py_EQ: c = size1 == size2; break;
+ case Py_NE: c = size1 != size2; break;
+ case Py_GT: c = size1 &gt; size2; break;
+ case Py_GE: c = size1 &gt;= size2; break;
+ }
+ result = c ? Py_True : Py_False;
+ Py_INCREF(result);
+ return result;
+ }
+</pre> </section> <section id="abstract-protocol-support"> <h2>
+<span class="section-number">3.5. </span>Abstract Protocol Support</h2> <p>Python supports a variety of <em>abstract</em> ‘protocols;’ the specific interfaces provided to use these interfaces are documented in <a class="reference internal" href="../c-api/abstract#abstract"><span class="std std-ref">Abstract Objects Layer</span></a>.</p> <p>A number of these abstract interfaces were defined early in the development of the Python implementation. In particular, the number, mapping, and sequence protocols have been part of Python since the beginning. Other protocols have been added over time. For protocols which depend on several handler routines from the type implementation, the older protocols have been defined as optional blocks of handlers referenced by the type object. For newer protocols there are additional slots in the main type object, with a flag bit being set to indicate that the slots are present and should be checked by the interpreter. (The flag bit does not indicate that the slot values are non-<code>NULL</code>. The flag may be set to indicate the presence of a slot, but a slot may still be unfilled.)</p> <pre data-language="c">PyNumberMethods *tp_as_number;
+PySequenceMethods *tp_as_sequence;
+PyMappingMethods *tp_as_mapping;
+</pre> <p>If you wish your object to be able to act like a number, a sequence, or a mapping object, then you place the address of a structure that implements the C type <a class="reference internal" href="../c-api/typeobj#c.PyNumberMethods" title="PyNumberMethods"><code>PyNumberMethods</code></a>, <a class="reference internal" href="../c-api/typeobj#c.PySequenceMethods" title="PySequenceMethods"><code>PySequenceMethods</code></a>, or <a class="reference internal" href="../c-api/typeobj#c.PyMappingMethods" title="PyMappingMethods"><code>PyMappingMethods</code></a>, respectively. It is up to you to fill in this structure with appropriate values. You can find examples of the use of each of these in the <code>Objects</code> directory of the Python source distribution.</p> <pre data-language="c">hashfunc tp_hash;
+</pre> <p>This function, if you choose to provide it, should return a hash number for an instance of your data type. Here is a simple example:</p> <pre data-language="c">static Py_hash_t
+newdatatype_hash(newdatatypeobject *obj)
+{
+ Py_hash_t result;
+ result = obj-&gt;some_size + 32767 * obj-&gt;some_number;
+ if (result == -1)
+ result = -2;
+ return result;
+}
+</pre> <p><code>Py_hash_t</code> is a signed integer type with a platform-varying width. Returning <code>-1</code> from <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_hash" title="PyTypeObject.tp_hash"><code>tp_hash</code></a> indicates an error, which is why you should be careful to avoid returning it when hash computation is successful, as seen above.</p> <pre data-language="c">ternaryfunc tp_call;
+</pre> <p>This function is called when an instance of your data type is “called”, for example, if <code>obj1</code> is an instance of your data type and the Python script contains <code>obj1('hello')</code>, the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_call" title="PyTypeObject.tp_call"><code>tp_call</code></a> handler is invoked.</p> <p>This function takes three arguments:</p> <ol class="arabic simple"> <li>
+<em>self</em> is the instance of the data type which is the subject of the call. If the call is <code>obj1('hello')</code>, then <em>self</em> is <code>obj1</code>.</li> <li>
+<em>args</em> is a tuple containing the arguments to the call. You can use <a class="reference internal" href="../c-api/arg#c.PyArg_ParseTuple" title="PyArg_ParseTuple"><code>PyArg_ParseTuple()</code></a> to extract the arguments.</li> <li>
+<em>kwds</em> is a dictionary of keyword arguments that were passed. If this is non-<code>NULL</code> and you support keyword arguments, use <a class="reference internal" href="../c-api/arg#c.PyArg_ParseTupleAndKeywords" title="PyArg_ParseTupleAndKeywords"><code>PyArg_ParseTupleAndKeywords()</code></a> to extract the arguments. If you do not want to support keyword arguments and this is non-<code>NULL</code>, raise a <a class="reference internal" href="../library/exceptions#TypeError" title="TypeError"><code>TypeError</code></a> with a message saying that keyword arguments are not supported.</li> </ol> <p>Here is a toy <code>tp_call</code> implementation:</p> <pre data-language="c">static PyObject *
+newdatatype_call(newdatatypeobject *obj, PyObject *args, PyObject *kwds)
+{
+ PyObject *result;
+ const char *arg1;
+ const char *arg2;
+ const char *arg3;
+
+ if (!PyArg_ParseTuple(args, "sss:call", &amp;arg1, &amp;arg2, &amp;arg3)) {
+ return NULL;
+ }
+ result = PyUnicode_FromFormat(
+ "Returning -- value: [%d] arg1: [%s] arg2: [%s] arg3: [%s]\n",
+ obj-&gt;obj_UnderlyingDatatypePtr-&gt;size,
+ arg1, arg2, arg3);
+ return result;
+}
+</pre> <pre data-language="c">/* Iterators */
+getiterfunc tp_iter;
+iternextfunc tp_iternext;
+</pre> <p>These functions provide support for the iterator protocol. Both handlers take exactly one parameter, the instance for which they are being called, and return a new reference. In the case of an error, they should set an exception and return <code>NULL</code>. <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code>tp_iter</code></a> corresponds to the Python <a class="reference internal" href="../reference/datamodel#object.__iter__" title="object.__iter__"><code>__iter__()</code></a> method, while <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code>tp_iternext</code></a> corresponds to the Python <a class="reference internal" href="../library/stdtypes#iterator.__next__" title="iterator.__next__"><code>__next__()</code></a> method.</p> <p>Any <a class="reference internal" href="../glossary#term-iterable"><span class="xref std std-term">iterable</span></a> object must implement the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code>tp_iter</code></a> handler, which must return an <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> object. Here the same guidelines apply as for Python classes:</p> <ul class="simple"> <li>For collections (such as lists and tuples) which can support multiple independent iterators, a new iterator should be created and returned by each call to <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code>tp_iter</code></a>.</li> <li>Objects which can only be iterated over once (usually due to side effects of iteration, such as file objects) can implement <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code>tp_iter</code></a> by returning a new reference to themselves – and should also therefore implement the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code>tp_iternext</code></a> handler.</li> </ul> <p>Any <a class="reference internal" href="../glossary#term-iterator"><span class="xref std std-term">iterator</span></a> object should implement both <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code>tp_iter</code></a> and <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code>tp_iternext</code></a>. An iterator’s <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iter" title="PyTypeObject.tp_iter"><code>tp_iter</code></a> handler should return a new reference to the iterator. Its <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code>tp_iternext</code></a> handler should return a new reference to the next object in the iteration, if there is one. If the iteration has reached the end, <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code>tp_iternext</code></a> may return <code>NULL</code> without setting an exception, or it may set <a class="reference internal" href="../library/exceptions#StopIteration" title="StopIteration"><code>StopIteration</code></a> <em>in addition</em> to returning <code>NULL</code>; avoiding the exception can yield slightly better performance. If an actual error occurs, <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_iternext" title="PyTypeObject.tp_iternext"><code>tp_iternext</code></a> should always set an exception and return <code>NULL</code>.</p> </section> <section id="weak-reference-support"> <span id="weakref-support"></span><h2>
+<span class="section-number">3.6. </span>Weak Reference Support</h2> <p>One of the goals of Python’s weak reference implementation is to allow any type to participate in the weak reference mechanism without incurring the overhead on performance-critical objects (such as numbers).</p> <div class="admonition seealso"> <p class="admonition-title">See also</p> <p>Documentation for the <a class="reference internal" href="../library/weakref#module-weakref" title="weakref: Support for weak references and weak dictionaries."><code>weakref</code></a> module.</p> </div> <p>For an object to be weakly referencable, the extension type must set the <code>Py_TPFLAGS_MANAGED_WEAKREF</code> bit of the <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_flags" title="PyTypeObject.tp_flags"><code>tp_flags</code></a> field. The legacy <a class="reference internal" href="../c-api/typeobj#c.PyTypeObject.tp_weaklistoffset" title="PyTypeObject.tp_weaklistoffset"><code>tp_weaklistoffset</code></a> field should be left as zero.</p> <p>Concretely, here is how the statically declared type object would look:</p> <pre data-language="c">static PyTypeObject TrivialType = {
+ PyVarObject_HEAD_INIT(NULL, 0)
+ /* ... other members omitted for brevity ... */
+ .tp_flags = Py_TPFLAGS_MANAGED_WEAKREF | ...,
+};
+</pre> <p>The only further addition is that <code>tp_dealloc</code> needs to clear any weak references (by calling <a class="reference internal" href="../c-api/weakref#c.PyObject_ClearWeakRefs" title="PyObject_ClearWeakRefs"><code>PyObject_ClearWeakRefs()</code></a>):</p> <pre data-language="c">static void
+Trivial_dealloc(TrivialObject *self)
+{
+ /* Clear weakrefs first before calling any destructors */
+ PyObject_ClearWeakRefs((PyObject *) self);
+ /* ... remainder of destruction code omitted for brevity ... */
+ Py_TYPE(self)-&gt;tp_free((PyObject *) self);
+}
+</pre> </section> <section id="more-suggestions"> <h2>
+<span class="section-number">3.7. </span>More Suggestions</h2> <p>In order to learn how to implement any specific method for your new data type, get the <a class="reference internal" href="../glossary#term-CPython"><span class="xref std std-term">CPython</span></a> source code. Go to the <code>Objects</code> directory, then search the C source files for <code>tp_</code> plus the function you want (for example, <code>tp_richcompare</code>). You will find examples of the function you want to implement.</p> <p>When you need to verify that an object is a concrete instance of the type you are implementing, use the <a class="reference internal" href="../c-api/object#c.PyObject_TypeCheck" title="PyObject_TypeCheck"><code>PyObject_TypeCheck()</code></a> function. A sample of its use might be something like the following:</p> <pre data-language="c">if (!PyObject_TypeCheck(some_object, &amp;MyType)) {
+ PyErr_SetString(PyExc_TypeError, "arg #1 not a mything");
+ return NULL;
+}
+</pre> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>Download CPython source releases.</dt>
+<dd>
+<p><a class="reference external" href="https://www.python.org/downloads/source/">https://www.python.org/downloads/source/</a></p> </dd> <dt>The CPython project on GitHub, where the CPython source code is developed.</dt>
+<dd>
+<p><a class="reference external" href="https://github.com/python/cpython">https://github.com/python/cpython</a></p> </dd> </dl> </div> </section> <div class="_attribution">
+ <p class="_attribution-p">
+ &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
+ <a href="https://docs.python.org/3.12/extending/newtypes.html" class="_attribution-link">https://docs.python.org/3.12/extending/newtypes.html</a>
+ </p>
+</div>