<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Guohao Dou on Medium]]></title>
        <description><![CDATA[Stories by Guohao Dou on Medium]]></description>
        <link>https://medium.com/@GuohaoDou?source=rss-c9de74c39719------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*SSdLw2fIWTeFJlMF.</url>
            <title>Stories by Guohao Dou on Medium</title>
            <link>https://medium.com/@GuohaoDou?source=rss-c9de74c39719------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 02:35:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@GuohaoDou/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Write C extensions for Python: A binary tree example]]></title>
            <link>https://medium.com/@GuohaoDou/write-c-extensions-for-python-a-binary-tree-example-57128b7b43fe?source=rss-c9de74c39719------2</link>
            <guid isPermaLink="false">https://medium.com/p/57128b7b43fe</guid>
            <category><![CDATA[c]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Guohao Dou]]></dc:creator>
            <pubDate>Thu, 28 Dec 2017 09:29:15 GMT</pubDate>
            <atom:updated>2017-12-28T09:29:15.590Z</atom:updated>
            <content:encoded><![CDATA[<p>I was first introduced to C extensions when reading through PyTorch source code. After a little bit of googling, I decided to write something slightly more useful than the examples given by <a href="https://docs.python.org/3/extending/extending.html">Python documentation</a>.</p><p>I have the habit to learning a new language by implementing a few commonly used data structures in it. And a binary tree is my pick for this one.</p><p>My binary tree will be able to:</p><ul><li>Insert an element.</li><li>Listify itself with in-order traversal.</li><li>Rebuild itself from a list.</li></ul><p>After all three methods are implemented, we will have a sorting algorithm with O(NlogN) complexity :)</p><p>Basically, I am defining a new class BinTree contained in module bintree. An empty tree is defined as None.</p><p>The source code is available in my GitHub <a href="https://github.com/haasdo95/C-ext-bintree">repo</a>.</p><h3>Type Definition</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cf7dda8060e6508a491a5221e7f0c6a/href">https://medium.com/media/6cf7dda8060e6508a491a5221e7f0c6a/href</a></iframe><p>Our BinTree struct contains its data, its left child, and its right child, all of the type PyObject*, which is basically a wild “any”. Also, it has PyObject_HEAD at its top, making it an “extended PyObject”. To register a member, its name, type, and offset in the C struct must be known.</p><p>Methods of the class are registered in a similar fashion. To register a method, its name and underlying C function must be specified. Also, the way it accepts arguments will be specified by the METH_ flags. For example, METH_VARARGS makes the underlying C function accept an “argument tuple”, which contains all the positional arguments passed in.</p><p>Member and method definition both make use of a NULL-terminator.</p><p>Nothing too fancy here, really.</p><h3>constructors/destructors</h3><p>Three functions are generally needed for a Python object.</p><ul><li>a function that allocates memory for the object.</li><li>a function that initializes fields for the object (__init__!)</li><li>a function that deallocates memory for the object.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/122ae08308bbc30048b3a28914eb7a85/href">https://medium.com/media/122ae08308bbc30048b3a28914eb7a85/href</a></iframe><p>Python manages objects by counting reference: a function gains access to an object by grabbing a reference to the object. When the number of references to an object hits zero, the object will be “destructed” and its memory could be safely reclaimed by the OS(by calling a few frees, e.g.).</p><p>When writing C extensions, we need to manually manage reference counting by explicitly calling Py_INCREF and Py_DECREF(two macros provided by the Python C API).</p><p>You may have noticed that Py_INCREF must be called on Py_None as well. That’s because the None is just another object. Failure to do so will cause the None to be deallocated, which is a fatal error since None doesn’t even live in heap memory.</p><p>As for the code, BinTreeDealloc frees the memory used by a post-order traversal. BinTreeNew calls the low-level tp_alloc functions (which I guess is pretty much a few mallocs) to grab enough memory for the type(whose length is already stored in the PyTypeObject, more on this later). We then fill out everything with None and return. BinTreeInit corresponds to the __init__ function in Python classes. It’s important to INCREF an object before it’s stored(e.g in self-&gt;data).</p><p>Then the Type Object is defined. It contains all the information about a type/class, with its members, methods, constructor/destructor filled out. This type object must be added by PyModule_AddObject to enable the creation of a BinTree object.</p><h3>Binary Tree Methods</h3><h4>Insert</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afacbd1139d017f88152bfe5e34614c8/href">https://medium.com/media/afacbd1139d017f88152bfe5e34614c8/href</a></iframe><p>The insert method takes in two arguments. The first is the new object to insert. The second is a comparator function. Since our binary tree could take arbitrary datatype for its data field, this comparator function takes in two objects and returns an integer: 1 for larger, 0 for equal and -1 for smaller. As you can see, the Python C API to call a Python function is pretty straight forward.</p><p>It’s kinda annoying to DECREF every time you “make” a Python object (by Py_BuildValue, for example). Since these functions transfer the ownership of the returned object to the caller (i.e. your function), it’s your responsibility to dispose of it: store it somewhere to handle it later, DECREF it, or pass it on.</p><p>To prevent memory leaks, we also need to DECREF the old pointer after assignment, as you can see from line 28–30.</p><p>It’s important to call INCREF before returning, since according to the Python ownership rule, you could only return an object you own.</p><h4>Listify</h4><p>This one is really plain. And you could see that the Python C API kindly provides the methods for manipulating a Python List object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e67ae70ff297aeb3159137127c6130f/href">https://medium.com/media/5e67ae70ff297aeb3159137127c6130f/href</a></iframe><h4>FromList</h4><p>This one is easy now that we have the insert method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9bcdb70364014cbbdcb6a6f52a39c69/href">https://medium.com/media/d9bcdb70364014cbbdcb6a6f52a39c69/href</a></iframe><p>Just run a for loop through the list passed in and keep inserting.</p><h3>Try it Out!</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34f6f3f7c6e50a76e46a85f60f948704/href">https://medium.com/media/34f6f3f7c6e50a76e46a85f60f948704/href</a></iframe><p>You should see,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*QITKtCc4Tuky4NTHXB4oPw.png" /></figure><p>An in-order traversal through a binary tree gives us a sorted list. As we could see:</p><pre>[-111, 999, 444, -222, 1] -&gt; [-222, -111, 1, 444, 999]</pre><p>as a sanity check that our little binary tree is working.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=57128b7b43fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>