<?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 Joffrey Bienvenu on Medium]]></title>
        <description><![CDATA[Stories by Joffrey Bienvenu on Medium]]></description>
        <link>https://medium.com/@joffreybvn?source=rss-782a755b2081------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*pmZK4U6zU6J1D_bmOUDFng.png</url>
            <title>Stories by Joffrey Bienvenu on Medium</title>
            <link>https://medium.com/@joffreybvn?source=rss-782a755b2081------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:35:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joffreybvn/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[Call paginated API with Airflow’s HttpOperator]]></title>
            <link>https://medium.com/apache-airflow/call-paginated-api-with-airflows-httpoperator-3ab5103472f8?source=rss-782a755b2081------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ab5103472f8</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[apache-airflow]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Joffrey Bienvenu]]></dc:creator>
            <pubDate>Wed, 15 Nov 2023 21:38:41 GMT</pubDate>
            <atom:updated>2023-11-15T22:42:13.394Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*itVniAsKCgw29JkODGhPyw.png" /></figure><p>Upcoming <strong>Airflow 2.8.0 </strong>has<strong> </strong>an improved <a href="https://registry.astronomer.io/providers/apache-airflow-providers-http/versions/4.7.0/modules/HttpOperator"><em>HttpOperator</em></a>, which allows to easily paginate over APIs — especially when they are not user-friendly !</p><p>In this quick article, we’ll go over:<br>⟶ <a href="#3d8c">What is Pagination ?</a><br>⟶ <a href="#9eb9">How to paginate with the HttpOperator</a></p><p><em>Note:</em> Purists can already give it a try by installing manually the <a href="https://pypi.org/project/apache-airflow-providers-http/">apache-airflow-providers-http</a> from pypi.</p><h3>What is Pagination ?</h3><p>When interacting with an API, it is common to pull and receive a lot of data. But maintainers of such API want to preserve a quick response time, saving CPU, Ram and bandwidth. Thus, the data will most likely be sent in multiple chunks — via a <strong>paginated</strong> API !</p><h4>Pagination for dummies</h4><p>How to deal with a paginated API ? Here is a quick course:</p><p>1️⃣ — Do a first call, without any parameters. Among the returned business data, you will eventually get the total number of entries available on the server, and the size of the chunk that you received.<br> 2️⃣ — Read the docs a bit further: look for <em>limit</em>, <em>skip</em>, <em>page </em>query parameters, or similar. Using them, you call the API again to receive the next chunk of data.<br> 🔄 — Repeat those calls until you get all data chunks.<br> 3️⃣ — Check when you reach the last page of the API. Based on the parameters you send and the given response, determine the stop condition.</p><p>Put everything in a software (using Airflow, of course) which calls the API repeatedly until the stop condition is met. Congrats !</p><p>In Airflow, when you know the total number of data chunks that an API will send you in advance— <em>when it’s a for loop</em> — , you can implement such software using <a href="https://airflow.apache.org/docs/apache-airflow/stable/authoring-and-scheduling/dynamic-task-mapping.html"><strong>dynamic tasks</strong></a><strong>.</strong></p><h4>Unfriendly API</h4><p>But what if the API does not tell you the total number of entries you are going to receive ? What if you can’t control the size of the data chunks ? What if you don’t have nice and human-readable parameters like <em>skip</em>, <em>page </em>or <em>limit </em>?</p><p>What if the API just sends you back some data, and a <em>random cursor id</em> or <em>page url</em> that you have to call to get the next chunk ? What if you can’t determine those parameters yourself — <em>What if it’s a ‘while’ loop ?</em></p><p>Relax ! Airflow got your back with the <strong>new pagination feature</strong> of the HttpOperator 🎉. Let’s see below how it works.</p><h3>Using the HttpOperator for pagination</h3><p>To illustrate the pagination feature of the HttpOperator, we’ll create an Airflow DAG which loads data from the <a href="https://dummyjson.com/">https://dummyjson.com</a> API.</p><h4>Writing the DAG</h4><p>Let’s start by creating a new dag: Open your favorite IDE, and create a new <em>dag.py</em> file with the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/191f37e2c9befb6774ca4ff193fa3063/href">https://medium.com/media/191f37e2c9befb6774ca4ff193fa3063/href</a></iframe><p>The above code defines the basic structure of an Airflow dag, which is composed of:</p><ul><li><strong>The imports</strong> — At the top of the file. Usual Python.</li><li><strong>The Dag definition</strong> — We name our dag “<em>extract_data</em>” and schedule it <em>daily </em>starting from <em>today.</em></li><li><strong>The Operators definition</strong> — Empty right now, we’ll complete it afterwards</li><li><strong>The flow logic</strong> — We won’t need it for this example</li></ul><h4>Adding the HttpOperator</h4><p>The <a href="https://dummyjson.com/">dummyjson API</a> has a /product endpoint, which returns chunked data. We can parameterize those chunks via the <em>limit </em>and <em>skip </em>attributes:</p><ul><li><strong><em>limit</em></strong>: Define the size of the chunk. <em>E.g</em>. A limit of <em>20 </em>will return a chunk of 20 entries.</li><li><strong><em>skip</em></strong>: Define how many entries to skip. <em>E.g.</em> Skipping <em>10 </em>will return data starting from the 11th entry.</li></ul><p>Let’s add the below code to your dag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3281c1b5ab232ae3bba73e982825fb2/href">https://medium.com/media/e3281c1b5ab232ae3bba73e982825fb2/href</a></iframe><p>In this code, we define the <em>load_api_data </em>task, which is an <strong>HttpOperator</strong>. we will execute <em>GET </em>requests on the <em>dummy_api</em>’s /product endpoint. We want chunks of <em>10 </em>entries starting with the first one. And by providing a <em>paginate </em>function, we effectively tell the Operator to do repeated call — until the <em>paginate </em>function returns None.</p><p>But the <em>paginate </em>function doesn’t exist yet 😱. We’ll create it in a minute !</p><h4>How does the pagination work ?</h4><p>The <em>paginate </em>function must be a Callable (function) which receives the <a href="https://github.com/psf/requests/blob/main/src/requests/models.py#L640">request.Response</a> from the previous call as input, and returns parameters defining how to execute the next API call.</p><p>As long as this function returns parameters, the HttpOperator will repeatedly call the API with those provided parameters. If the function returns None, the HttpOperator stops its execution and returns the accumulated data.</p><p>The format of the returned parameters must be a nested dictionary with the following optional keys: <em>endpoint</em>, <em>data</em>, <em>headers </em>and <em>extra_options</em>. <strong>Those keys are identical to the parameters of the </strong><a href="https://registry.astronomer.io/providers/apache-airflow-providers-http/versions/4.7.0/modules/HttpOperator"><strong>HttpOperator</strong></a>, because they will be merged and will override the ones supplied initially in the Operator declaration.</p><h4>Adding the pagination function</h4><p>Let’s add the pagination function. Copy the below code at the top of your <em>dag.py</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e524065052f542ba0194c87c4aecad4d/href">https://medium.com/media/e524065052f542ba0194c87c4aecad4d/href</a></iframe><p>This function does three things:</p><ul><li>Receives a <a href="https://github.com/psf/requests/blob/main/src/requests/models.py#L640">request.Response</a> object, from which the <em>total</em>, <em>skip </em>and <em>limit </em>fields are retrieved. Those fields are returned from the API as JSON.</li><li>Checks if there is remaining data to pull: The API indicates us how many entries are available in total, via the <em>total </em>field. As long as the number of entries we pulled ( skip + limit ) is lower than the total number of data available, we have to pull again.</li><li>✔️ <strong>If it’s the case:</strong> we define new parameters for the next call: skipping 10 more entries. <em>Note</em>: <strong>We don’t need to specify the <em>limit </em>parameter.</strong> When a parameter is not overridden, it uses the one provided by the previous call (in this case, the initial call).<br>❌ <strong>If it’s not the case</strong>: None is returned.</li></ul><h4>Wrapping everything together</h4><p>All pieces are aligned and ready for testing. Push your dag onto your Airflow instance, and let the magic happen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c0Hoz36LmsWotaJeoWCFiw.png" /></figure><p>The <em>HttpOperator</em> is looping, getting all the data, and log them on the console at the end of its execution. Congrats ! 🎉</p><h3>Limitation</h3><p>Before letting you go, beware that the <em>HttpOperator </em>is <strong>accumulating the results of your calls in memory</strong>. The sum of all paginated data is returned in one go at the end of the operator&#39;s execution.</p><p>If you load multiple GBs of data, you need a strong backend (a machine, VM or Pod with enough memory / Ram). Otherwise the Operator may crash, causing a data loss…</p><p>Thanks for reading! Any feedback, questions or whatever you want to share is welcome. You can also reach me directly on the <a href="https://apache-airflow-slack.herokuapp.com/">Airflow’s Slack</a>. 💬</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ab5103472f8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-airflow/call-paginated-api-with-airflows-httpoperator-3ab5103472f8">Call paginated API with Airflow’s HttpOperator</a> was originally published in <a href="https://medium.com/apache-airflow">Apache Airflow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enable Kerberos with Airflow KubernetesExecutor]]></title>
            <link>https://medium.com/apache-airflow/enable-kerberos-with-airflow-kubernetesexecutor-6e86621e97a5?source=rss-782a755b2081------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e86621e97a5</guid>
            <category><![CDATA[kerberos]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[sidecar]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Joffrey Bienvenu]]></dc:creator>
            <pubDate>Fri, 09 Jun 2023 09:05:39 GMT</pubDate>
            <atom:updated>2023-06-16T19:38:32.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Kerberos (Cerberus), Hades’ dog defending Airflow" src="https://cdn-images-1.medium.com/max/794/1*NJfUjIHpJAnyNG5yfNwU_g.png" /><figcaption>Kerberos guards Airflow — Dog icon from <a href="https://www.svgrepo.com/">svgrepo.com</a></figcaption></figure><p>While the integration of Kerberos sidecar with the CeleryExecutor works smoothly out of the box in Airflow 2.6.0, further configuration is required when using the KubernetesExecutor and CeleryKubernetesExecutor<strong> to shutdown the Kerberos sidecar attached to the main container</strong>.</p><p>In this article, we will see a practical example of pod_template_file and introducing two necessary entrypoints that need to be added to the Airflow image, in order to use the Kerberos sidecar with KubernetesExecutor.</p><h3>Sidecar shutdown problem</h3><p>When using the KubernetesExecutor in conjunction with a sidecar, the following sequence of events occurs within the Pod:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*87RXNwBuePE0jeACcmbQuw.png" /><figcaption>The sidecar still up and running while the main container exited — Image by author</figcaption></figure><ol><li>The main container, also referred to as the “base” container, initiates and begins executing its designated task.</li><li>Simultaneously, the sidecar container starts alongside the main container. In our case, it will create a ticket from a Kerberos keytab and schedule a refresh every hour.</li><li>When the main container completes its task, it gracefully exits, signaling the end of its execution to Kubernetes.</li><li>However, despite the main container’s graceful exit, the <strong>sidecar container continues to run, causing the Pod to remain active</strong> indefinitely.</li></ol><h3>Solution: Communicate the exit signal to the sidecar</h3><p>To terminate the Pod, the sidecar needs to receive the exit signal.</p><p>To do so, we need to establish communication between the main ‘base’ container and the sidecar. So that an EXIT signal can be passed from the former to the latter. There are two approaches to achieve this:</p><ul><li><strong>Shared Process</strong>: This first method uses the shareProcessNamespace functionality to pass an exit signal directly into the sidecar container.</li><li><strong>Shared Volume with File</strong>: This second approach, which we will explore in this article, leverages a shared volume to facilitate communication. Specifically, it involves utilizing a file stored on the shared volume as a means of exchanging information between the main ‘base’ container and the sidecar. <strong>It works well in environments with restricted permissions</strong>, where using shareProcessNamespace may not be feasible.</li></ul><h3>Adding a Pod Template</h3><p>The following Pod template introduces several enhancements to <a href="https://airflow.apache.org/docs/apache-airflow/2.6.1/core-concepts/executor/kubernetes.html#example-pod-templates">the “dag in PersitentVolume example template” proposed by Airflow</a>:</p><ul><li><strong>Sidecar Container</strong>: The Pod template includes a Kerberos sidecar container, working in tandem with the main ‘base’ container. Again, this sidecar create a ticket from a Kerberos keytab and schedule the refresh every hour.</li><li><strong>Volumes and VolumeMounts:</strong> To facilitate the integration of Kerberos dependencies (keytab, krb5.conf, …), the Pod template defines the necessary volumes and VolumeMounts.</li><li><strong>‘exit-signals’ Volume</strong>: To coordinate the termination of the main ‘base’ container and the sidecar, an ‘exit-signals’ volume is created. It enables the main container to pass an exit signal via file to the sidecar.</li><li><strong>Custom Container Entrypoints</strong>: The Pod template also incorporates custom container entrypoints. Let’s see further below what they do. ⬇️</li></ul><h4>The Pod Template:</h4><p><strong>Note</strong>: This is an example of template, not usable as-is. Take care to replace the image, secret, PVC and configMap names by your own.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d84a40d0d9369a4be258d40cc6aebfdd/href">https://medium.com/media/d84a40d0d9369a4be258d40cc6aebfdd/href</a></iframe><h3>Adding entrypoints</h3><p>To pass the EXIT signal between the main ‘base’ container and the sidecar, we define specific entrypoints for the worker and the sidecar. They need <strong>to be added in the Docker image</strong> of your Airflow setup.</p><h4>Worker entrypoint:</h4><p>The custom entrypoint for the Worker has two functionalities:</p><ol><li><strong>Execute Airflow Command</strong>: The script utilizes the ( $@ ) command to execute the Airflow command received from the scheduler. It can actually be any valid Airflow command, such as triggering a task, running a DAG, or performing other workflow-related operations.<br><strong>Note</strong>: Do not use exec . In a nutshell, exec prevent any subsequent line of your bash script to be executed.</li><li><strong>Create “EXIT” File</strong>: Following the execution of the Airflow command, the script creates a file named “EXIT” within the shared volume. This file serves as an exit signal and its presence indicates to the sidecar container that the Airflow worker has completed its task and is ready for termination.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c0c96711b19f8f4716de29a339418b7/href">https://medium.com/media/0c0c96711b19f8f4716de29a339418b7/href</a></iframe><h4>Sidecar entrypoint:</h4><p>The second entrypoint, for the sidecar, operates in conjunction with the worker. Let’s see what it does:</p><ol><li><strong>Start Airflow Sidecar</strong>: The script launches the Airflow sidecar container via nohup airflow kerberos. The <em>nohup</em> command launch the Kerberos ticket refresh in a subprocess.</li><li><strong>Catch subprocess Id</strong>: The echo $! &gt; kerberis.pid and CHILD_PID=$(cat kerberos.pid ) lines are catching the Id of the subprocess, so that the next part of the script can interact with it.</li><li><strong>Monitor for Termination Signal</strong>: An infinite loop continuously checks for the presence of an “EXIT” file in the /opt/exit-signals folder. When detected, the script terminate the Kerberos subprocess by killing the $CHILD_PID.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/15702bf5fc1d16c0cb2310eea7c816b2/href">https://medium.com/media/15702bf5fc1d16c0cb2310eea7c816b2/href</a></iframe><p>And that’s it ! You have now Kerberos ticket refresh both with the <strong>KubernetesExecutor</strong> and the <strong>CeleryKubernetesExecutor </strong>🎉</p><p>The integration of Kerberos sidecar support with Airflow presents new opportunities for secure and efficient workflow execution in Kubernetes environments. With the shared volume approach and custom entrypoints, communication between the main ‘base’ container and the sidecar becomes seamless, enabling secure data workflows and streamlined Kerberos management.</p><p><strong>Credits</strong>: <a href="https://github.com/jedcunningham">Jed Cunningham</a>, <em>Airflow PMC member</em>, for pointing out this solution on Airflow Slack. <a href="https://github.com/stevenaldinger/">Steven Aldigen</a>, writer of this <a href="https://medium.com/teamsnap-engineering/properly-running-kubernetes-jobs-with-sidecars-ddc04685d0dc">nice Medium article about EXIT signals on Kubernetes</a>. And the Stackoverflow community for <a href="https://stackoverflow.com/questions/20254155/how-to-run-nohup-and-write-its-pid-file-in-a-single-bash-statement">detailling how using nohup</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e86621e97a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/apache-airflow/enable-kerberos-with-airflow-kubernetesexecutor-6e86621e97a5">Enable Kerberos with Airflow KubernetesExecutor</a> was originally published in <a href="https://medium.com/apache-airflow">Apache Airflow</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep dive: Create and publish your first Python library]]></title>
            <link>https://medium.com/data-science/deep-dive-create-and-publish-your-first-python-library-f7f618719e14?source=rss-782a755b2081------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7f618719e14</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[libraries]]></category>
            <category><![CDATA[pypi]]></category>
            <category><![CDATA[creation]]></category>
            <dc:creator><![CDATA[Joffrey Bienvenu]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 15:42:52 GMT</pubDate>
            <atom:updated>2021-01-15T11:20:42.950Z</atom:updated>
            <content:encoded><![CDATA[<h4>A complete guide for the creation of a Python library, from zero to CI/CD pipeline and automatic documentation generation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KRZB1eJtt_3zyqvraKO12A.png" /><figcaption>Photo by <a href="https://unsplash.com/@juliphjuli?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Juliya Zemlyanaya</a> on <a href="https://unsplash.com/s/photos/jellyfish-dive?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a> — Package icon made by <a href="https://www.flaticon.com/authors/freepik">Freepik</a> from <a href="http://www.flaticon.com/">www.flaticon.com</a></figcaption></figure><p>Do you want to create a library and share your code with the entire world? Fantastic! In this article, we will deep dive into the creation of a library, and we’ll see in detail how to:</p><p>— Write quality code to be published as a library. <br>— Host your library on Pypi. <br>— Tests and deploy your futures updates with a CI/CD pipeline.<br> — Generate a documentation website automatically from your code. <br>— And finally, host this doc for free on ReadTheDocs.</p><p>At the end of your reading, the world of libraries and how to maintain them in the long run, will no longer hold any secrets for you!</p><p>But first, let’s see when and why to create a library:</p><h3>When to create a library?</h3><p>When you have just finished a long project, full of pitfalls, where you felt sometimes helpless to solve certain situations; You had to search deep among the least upvoted posts of StackOverflow, and, as a result, you have produced many chunk of code that solve concrete problems.</p><p>At this point, <strong>you have the possibility to create a library</strong>: You will only have to copy some code from your project. Easy!</p><h3>Why create a library?</h3><p>First, because the code you have written may, in the future, save other developers from going through the same long and expensive research process you did.</p><p>Also, if your code provides a high level interface to solve some problems, you will help democratize the resolution of these problems to less experienced programmers. Therefore, your high-level library could, for example, become an entry point for others to easily get a quick result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tKg2iTnZj43pSl79Y1-8_A.png" /><figcaption>Convinced recruiters — Photo by <a href="https://unsplash.com/@wocintechchat?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Christina @ wocintechchat.com</a> on <a href="https://unsplash.com/s/photos/interview?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>And finally, because on your resume and during an interview, saying that you devote your free time to programming and developing libraries will undeniably work in your benefit.</p><p>Confident? Let’s go to the creation of your lib!</p><h3>Get started: Maximize compatibility</h3><p>First, when creating your library’s project in your favorite IDE, use an older version of Python, so that your library can be compatible with as many current workflows as possible.</p><p>For example: Python 3.9 released 2 months ago. If you decide to start with this new Python and use the new features of this version, only developers who have applications already running Python 3.9 will be able to use your library… So, very few people!</p><p>So, go back a few versions and take <strong>Python 3.6</strong>.</p><h3>Write down your code</h3><p>To keep this article simple, you will create a library that will multiply one number by another. Nothing more.</p><h4>1. Start with a script</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a34afa0f6eaa8fedc8805d7bb52d3eda/href">https://medium.com/media/a34afa0f6eaa8fedc8805d7bb52d3eda/href</a></iframe><p>Writing code always begins, in one way or another, with writing a small script. Like this one on the left.</p><p>At <em>line 8</em>, the print will display the number <em>10</em>.</p><h4>2. Refactor to a function</h4><p>This step is very simple: turn your script into a nice documented function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e4913e1ed093983f4017428350d284b5/href">https://medium.com/media/e4913e1ed093983f4017428350d284b5/href</a></iframe><p><strong>You must document your code, now! </strong>Be brave, and do it. Here is why:</p><p>Later in this article, we will automatically generate a website with documentation based on the docstring (the specifications) of your functions. If you don’t write your doc now, you’ll have to do it later, by going over all your code again and trying to remember what each line does. This will be even longer and more boring…</p><p>In addition, for novice developers, documenting your functions helps you to better cut out and locate what each piece of code does. This will make it easier for you to create Objects later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dhUaNFsYJMVV2d9m6wd2Qw.jpeg" /><figcaption>Relax, you’ve written Object-Oriented code — Photo by <a href="https://unsplash.com/@goshua13?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joshua Aragon</a> on <a href="https://unsplash.com/s/photos/code?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>3. Transform to an Object</h4><p><em>Disclaimer:</em> The following code is certainly overkill. But for the demonstration, we transform the previous function into an object.</p><p>The Object-Oriented Programming (OOP) makes the maintainability of your code easier for you, for you in 6 months, and for the developers who will contribute to your library.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/917f0b2bb16377b304222d5ce3197b1f/href">https://medium.com/media/917f0b2bb16377b304222d5ce3197b1f/href</a></iframe><p>But the main reason to write OOP is that when you develop a library, you need to think about: <strong>What is the architecture that will make my library as easy to use as possible?</strong></p><p>You have to put yourself in the user’s shoes by thinking about how you use other libraries: You usually import it, then you type one or two lines of code to, and that’s it!</p><p>Try to make your library easy to use, and Pythonic. If you imagine things simply for the user, you will write your code in a clearer way, and it will be easier to maintain in the long run.</p><h3>Organize your library</h3><p>The code of your library is complete. Now you need to organize it so that it is ready to be published.</p><h4>1. Create a Python package</h4><p>Create a python package and name it as you want users to import your library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/552/1*xpAL7SPExb_CpohxP5sf9w.png" /><figcaption>Creation of a Python package with PyCharm — Image by author</figcaption></figure><p>For example, we will create the package “<em>medium_multiply</em>”. It will contain all the code of our library. And other developers will be able to import the library by writing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c62d5da749c394d42e9477a49de0a715/href">https://medium.com/media/c62d5da749c394d42e9477a49de0a715/href</a></iframe><h4>What is a Python package?</h4><p>A Python package is simply a folder with an empty “<em>__init__.py</em>” file inside. Some IDEs offer to create a package directly, and take care of creating the init file for you.</p><p>All Python files, objects, functions and variables created in a package can be imported from anywhere in your project.</p><h4>2. Move your class to its own file</h4><p>So far, you have probably written your code in a “<em>main.py</em>” or “<em>app.py</em>” file at the root of your project. But only the code present in the “medium_multiply” package will be published.</p><p>So now, you need to copy the “<em>Multiplication</em>” class into a new file “<em>medium_multiply/multiplication.py</em>”. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*XKXwFM4d047h7Y4gED1zfQ.png" /><figcaption>Example of the Multiplication class moved to <strong>multiplication.py</strong>. Code stay the same.</figcaption></figure><h4>3. Call your library</h4><p>You can now start using your library as if you were a user, by importing it into your “main.py”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f229ab943bb690ac4ed02bdd8084980/href">https://medium.com/media/6f229ab943bb690ac4ed02bdd8084980/href</a></iframe><p>Et voilà! You have finished creating the architecture of your library.</p><h4>Bonus: Prettify the import</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/213c540dbcb16b4dfa64f9b7be99d64b/href">https://medium.com/media/213c540dbcb16b4dfa64f9b7be99d64b/href</a></iframe><p>The way the “<em>Multiplication”</em> class is imported is long and disgraceful… Wouldn’t it be shorter and prettier to import it just like <em>line 5</em>?</p><p>To archieve that, just add the following line of code in the “<em>__init__.py</em>” file of your Python package:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1afa10a3ed9973bd0bf9acb86760d6c5/href">https://medium.com/media/1afa10a3ed9973bd0bf9acb86760d6c5/href</a></iframe><p><strong>Warning:</strong> If you import a lot of classes into this file, the order of the declarations can be important! Especially when your classes need other parent classes to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eg1EfJFEfErnZrO4FRKkTw.png" /><figcaption>Your library passing the tests — Photo by <a href="https://unsplash.com/@john_cameron?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">John Cameron</a> on <a href="https://unsplash.com/s/photos/hurdle-race?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Writing the tests</h3><p>When you publish your library to the world, developers like to have documentation and examples. It’s much easier to copy an example than to read the whole specification!</p><p>Sooner or later you will have to write these examples… And sooner rather than later, your examples may simply be a copy/paste of the tests that you are going to write now.</p><h4>1. Create a tests package</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*VrbpSaDtsAZx33dmgu6w0g.png" /><figcaption>The “tests” package and its content — Image by author</figcaption></figure><p>Create a new “<em>tests</em>” package at the root of your project. Inside, create a new file called “<em>multiplication_tests.py</em>”.</p><p>The architecture of your project should look like the image on the left.</p><h4>2. Write down your tests</h4><p>If you are not used to it, writing code that tests all cases can be long and boring. Fortunately, for this article, you just need to copy the following code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4517c8151aeb7f61293937f54e1fcec3/href">https://medium.com/media/4517c8151aeb7f61293937f54e1fcec3/href</a></iframe><p>Here we use “<em>unittest</em>” and “<em>math</em>”, two built-in Python libraries (no installation needed).</p><p>The Multiplication object is imported from the library too, and instantiated <em>line 9</em>. Our tests will be multiplications by 2.</p><p><em>Line 16</em>, we first test, the multiplication by 0, which should be 0.</p><p>Then, <em>line 23</em>, the multiplication of 5 by 2, which should be equal to 10.</p><p><em>Line 30</em>, the multiplication of a negative number, -7 by 2, which should be equal to -14.</p><p>Later, <em>line 37</em>, we tests a non-periodic rational number, (6/17) multiplied by 2.</p><p>Last but not least, on <em>line 44</em>, PI multiplied by 2. Because why not?</p><p>And the last two lines of this file are the entry point of the script: They will launch the execution of the tests.</p><h4>3. Run the tests</h4><p>You just wrote all your tests! Now all you have to do is run them. With PyCharm, just press one of the green buttons displayed in your file, or run the launcher on the top right corner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*0PRUs_eavFtIgHIEOwyeCw.png" /><figcaption>Running the tests in PyCharm — Image by author</figcaption></figure><p>You can also run the tests by typing this line directly in your console:</p><pre>python -m unittest -v tests/multiplication_tests.py</pre><p>Once executed, an “OK” is displayed in the console. This means that your code has passed all the tests without error. Congratulations!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*S7H_h__n36CKUHg6eYWbxg.png" /><figcaption>All tests passed — Image by author</figcaption></figure><h3>Adding a dependency</h3><p>You will rarely write a library that has no dependencies, that does not use any other existing library. In order to stick a little closer to the reality, you will now import and use NumPy to do the multiplications.</p><h4>1. Edit your code</h4><p>Adding and using NumPy in our Multiplication class is very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67652490294368aa71329db91064be5e/href">https://medium.com/media/67652490294368aa71329db91064be5e/href</a></iframe><p>For clarity, the docstring of this example has been removed.</p><p>On <em>line 2</em>, numpy is imported and renamed “np”.</p><p>The <em>line 12</em>, which executes the multiplication and returns the result, is replaced: <a href="https://numpy.org/doc/stable/reference/generated/numpy.dot.html">np.dot()</a> is now used to multiply one number by another.</p><h4>2. Add a requirements.txt</h4><p>The <em>requirements.txt</em> file is used in each Python project to specify its dependencies. So you can create one at the root and add a line with “<em>numpy</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/461/1*86nHfVJTz_AhJoTVxJlXmA.png" /><figcaption>A<strong> requirements.txt</strong> with numpy — Image by author</figcaption></figure><h4>3. Run the tests again</h4><p>After each modification of the code, you must run your tests. In our case, the tests pass without any problem. Your library is almost ready to be published! Let’s go to the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2kDZ_mlsORwZ1ucAGU50Pw.png" /><figcaption>Prepare for the launch — Photo by <a href="https://unsplash.com/@spacex?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">SpaceX</a> on <a href="https://unsplash.com/s/photos/rocket-launch?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Prepare for the launch</h3><p>You’re now going to set up a pipeline that, every time you push a modification on GitHub, will automatically:</p><p>— Run the tests.<br> — Publish the library update on <a href="https://pypi.org/">Pypi</a>.</p><p>All this requires the addition of a few files to your project.</p><h4>1. Add a .gitignore for Github</h4><p>First of all, the code of your library needs to be published somewhere where everyone can read it and modify it, if they want to. Because a living library is open-source, so that everyone can propose and discuss modifications. For this, we will naturally use <a href="https://github.com/">Github</a>.</p><p>And to avoid unnecessary files being added to your repository (e.g: PyCham config, or your Python env), you will add a “<em>.gitignore</em>” file to the root of your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*_DVPqrVbedr_pqHHzGwLxA.png" /><figcaption><a href="https://gitignore.io/">gitignore.io</a>, automatically create .gitignore — Image by author</figcaption></figure><p>You can do this on PyCharm with the .ignore plugin. Or by generating a file via gitignore.io, which you then copy to a “<em>.gitignore</em>” file. <a href="https://www.toptal.com/developers/gitignore/api/windows,macos,linux,intellij+all,git,visualstudiocode">Link to generate the file</a>.</p><h4>2. Write a welcoming README.md</h4><p>At the root of your project, create a “<em>README.md</em>” file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff8c57e7c29f6eac5030a2b8e459cc36/href">https://medium.com/media/ff8c57e7c29f6eac5030a2b8e459cc36/href</a></iframe><p>This file will be displayed on the <a href="https://pypi.org/">Pypi</a> page of your project, the one that developers visit when they search for new packages.</p><p>It is therefore important that your README is welcoming and that it summarizes in a few lines how to install and use your library!</p><p>You can write it quickly by copying the code from your “<em>main.py</em>” and adding a few titles, like in this example.</p><h4>3. The most important: A setup.py</h4><p>The “<em>setup.py</em>” file is specific to the creation of a library: It will indicate to Pypi (the Python Package Index) the version of your library, as well as a lot of other metadata for its referencing.</p><p>This way, developers will be able to install your package automatically with the following command:</p><pre>pip install medium-multiply</pre><p>Here is the content that you can copy in a new “<em>setup.py</em>” file at the root of your project:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/683100280025c8966cf76bca7b860271/href">https://medium.com/media/683100280025c8966cf76bca7b860271/href</a></iframe><p>In this file, up to <em>line 6</em>, we first have the imports.</p><p>Then, up to <em>line 13</em>, we load the content of the previously created README.md into a variable. This way, the content of your readme will be displayed on Pypi.</p><p>In line 17 and following, we give the library a name, a version and a short description.</p><p>Further on, <em>line 22</em>, we specify the URL of the website we are going to create next. Followed by the author, the email.</p><p>The classifiers, <em>line 26</em>, are simply tags for referencing on Pypi.</p><p>And finally, <em>line 37</em>, we load the “<em>medium_multiply</em>” package, which is the heart of the library. And we specify again the dependencies of this library with “<em>numpy</em>” on <em>line 39</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*odP4q31Rs_Gpt2h5xfrFVw.png" /><figcaption>Manually publishing your library — Photo by <a href="https://unsplash.com/@andriklangfield?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Andrik Langfield</a> on <a href="https://unsplash.com/s/photos/build?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>The first publish: manually</h3><p>Before creating an automatic publishing process, <strong>your library must be manually sent to Pypi</strong> at least once. To do this, you need the “<em>twine”</em> package, a collection of utilities which makes the publication of libraries easier. Install it with the following command:</p><pre>pip install wheel<br>pip install twine</pre><h4>1. Compile your library</h4><p>You are now ready to build your library. Type the following command in your console:</p><pre>python setup.py sdist bdist_wheel</pre><p>And let the magic happen: Several folders appear in your project. Don’t worry about the mess they create, <strong>you will be free to delete</strong> all of these once your library has been sent to Pypi for the first time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*viyNobnB8kWh5T4pxVOvxQ.png" /><figcaption>Three new folders were created — Image by author</figcaption></figure><p>These folders contain many files: In the “<em>dist</em>” folder, you will find the packaged version of your library.</p><p>These are the two files that will be sent to Pypi.</p><h4>2. Check the build</h4><p>But before, you can check if the build went well with this short command:</p><pre>twine check dist/*</pre><p>The console prints two lines with “PASSED”. Your library is ready to take off!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*gVGqDCOuRZYPOsjhAzJmTw.png" /><figcaption>Twine check PASSED, your library is ready — Image by author</figcaption></figure><h4>3. Upload to Test Pypi</h4><p>You are now ready to upload your library on Pypi. You will first upload it on the Test Pypi, in order to check, once again, that everything is correct. If it is not already done, create an account on <a href="https://pypi.org/">Pypi</a> and on <a href="https://test.pypi.org/">Test Pypi</a>. Then, type:</p><pre>twine upload --repository-url <a href="https://test.pypi.org/legacy/">https://test.pypi.org/legacy/</a> dist/*</pre><p>Test Pypi is a very useful tool: It allows you to publish, test and make mistakes, without having any influence on your packages published on the real Pypi.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/661/1*P1MA5YT8_Bs6Lb-D1x_ZqQ.png" /><figcaption>Your package successfully uploaded to Test Pypi — Image by author</figcaption></figure><p>After you entered the command, you will be asked to login with the username and password you provided when you created your account. Your library is then uploaded to Test Pypi. As a confirmation, the link of the newly created page is displayed. Congratulations!</p><h4>4. Upload to Pypi</h4><p>Are you satisfied with the result? Let the world discover your library: publish it on the real Pypi.</p><pre>twine upload dist/*</pre><p>Type the command above, connect to Pypi and voilà! Your library is published. Anyone can now download and install it with “<em>pip install medium-multiply</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1fbSNFcOzCMzduqn11rgQ.png" /><figcaption>The Pypi page of your amazing library — Image by author</figcaption></figure><h3>Continuous deployment</h3><p>You have just completed the manual upload process. It’s time to automate it with Travis, a free CI/CD tool for public repositories hosted on Github.</p><p>You can already create an account on <a href="https://travis-ci.com/">Travis CI.com</a>, and connect it to your Github account.</p><h4>1. Increment your library version</h4><p>We will publish an update of your library. To do so, <strong>you must first increment its version</strong> in the “<em>setup.py</em>” file: Replace “0.1.0” by “0.1.1”, for example.</p><h4>2. Create a .travis.yml file</h4><p>When you publish your project on Github, Travis will download it to its servers and execute the instructions written in a “<em>.travis.yml</em>” file. Go ahead, create this new file at the root of your project, and copy the following lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/656e025b9f20b2448e6b4a1527edce18/href">https://medium.com/media/656e025b9f20b2448e6b4a1527edce18/href</a></iframe><p>In this file, <em>line 3</em>, we first tell Travis which version of Python to use.</p><p>On <em>line 8</em>, we update pip.</p><p>We install the dependencies of our library (<em>line 11</em>), so that Travis can run our tests (<em>line 14</em>).</p><p>Finally, from <em>line 16</em>, we tell Travis to use a token to deploy the master branch of our repo on Pypi. This chunk of code is the one that will automatically build and upload the library.</p><p>The commands in this file will be executed one after the other. If one of them returns an error (e.g. Your tests fail), Travis will stop without executing the following ones.</p><p>This way, each time you push a new version of your library, you are sure that <strong>it will be deployed and sent to Pypi only if it passes the tests</strong>! This is a good way to make sure that other developers only receive working versions of your library.</p><h4>3. Get your Pypi token</h4><p>You need to give Travis your Pypi token, so he can login to your account to update the library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*2Bc94YEsCYB-2D5fZo7xWw.png" /><figcaption>Add API token on Pypi — Image by author</figcaption></figure><p>Go to the Pypy website. In the “<em>Account settings</em>” category, click on the “<em>Add API token</em>” button.</p><p>Give a name to your token (e.g. “Travis deployment”). In the “<em>Scope</em>” field, choose the library you just uploaded.</p><p>Then click on “<em>Add token</em>”. Your token is displayed,<strong> write it down</strong> ! If you close this web page without saving it, you will have to generate another one.</p><h4>4. Share on Github</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*ugUapiYZ9CVs_wFUEJlS2w.png" /><figcaption>PyCharm: share a project on Github — Image by author</figcaption></figure><p>Now publish your project on Github, in a public repository.</p><p>Make sure that the main branch of your repo is “master”. You can change this setting on Github.</p><p>You prefer to name your branch “<em>main</em>”? No worries. Just replace the last line of the “<em>.travis.yml</em>” file with “<em>branch: main</em>”.</p><h4>5. Update your Travis</h4><p>Login to your account on <a href="https://travis-ci.com/">Travis-ci.com</a>. A build should be in progress, and will end with an error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2vBFmitJCwgW6kTHFOqfQ.png" /><figcaption>Your first Travis build failed. See the “<strong>More options</strong>” button in the top right corner — Image by author</figcaption></figure><p>This is fine! Travis couldn’t connect to Pypi to upload your library because he doesn’t have your token yet. So let’s add it: Click on the “<em>More options</em>” button (visible at the top right of the image), then on “<em>Settings</em>”.</p><p>Find the “<em>Environment Variables</em>” section, and add a new variable named “<em>PYPI_TOKEN</em>” with your previously created Pypi token as value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/1*-ltczz2lCeCxq4kWkax2Ag.png" /><figcaption>Adding a PYPI_TOKEN variable with your Pypi token as value — Image by author</figcaption></figure><p>You can now go back to the previous page and click on “<em>Restart build</em>”. Wait for a few seconds, you will see a green “Build passed” appearing.</p><p>You have just set up the continuous integration and continuous deployment. From now on, every time you will push on your “<em>master</em>” branch, <strong>Travis will automatically run the tests and publish the update of your library</strong> on Pypi. Congratulations!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ylZpThbPXAhBPtX639KX3Q.png" /><figcaption>Lift-off ! Your library is on the web — Photo by <a href="https://unsplash.com/@spacex?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">SpaceX</a> on <a href="https://unsplash.com/s/photos/rocket-lift-off?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a>, package and v-mark icons made by <a href="https://www.flaticon.com/authors/freepik">Freepik</a> from <a href="http://www.flaticon.com/">www.flaticon.com</a></figcaption></figure><h3>Documentation hosted on the web, automatically</h3><p>Now, you will set up a system that hosts documentation on <a href="https://readthedocs.org/">readthedocs.org</a>, a free service, with <a href="https://pypi.org/project/Sphinx/">Sphinx</a>, a python package to generate doc. And of course, you want this system to update the documentation automatically.</p><p>This way, you will have almost nothing to write by hand. Just copy and paste some of your tests from time to time to make examples. And add here and there a short sentence of explanation.</p><p><strong>Reminder:</strong> Your library does not exist, if it is not documented. How could other developers use it if they have no idea of what to type?</p><h4>1. Install Sphinx</h4><p>Let’s start by installing the sphinx package, with the following command:</p><pre>pip install sphinx</pre><p>Now, create and access a “docs” folder at the root of your project. I recommend that you do this on the command line because you will then have to run Sphinx via the console:</p><pre>mkdir docs<br>cd docs</pre><h4>2. Setup your documentation</h4><p>It’s time to create all the necessary files to generate your documentation site. And Shpinx will do it for you, thanks to this command:</p><pre>sphinx-quickstart</pre><p>You can use the default settings of Sphinx. But be careful <strong>to specify the name of your project </strong>(here “<em>Medium Multiply</em>”), and your name as author.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*EIKEzi2hmIQPJOJHV4jVqw.png" /><figcaption>Specifying the Project name and Author with sphinx-quickstart — Image by author</figcaption></figure><p>Once the installation is complete, you will see some files and folders appear in your “<em>docs</em>” folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*mdUELRCt94SO757eS9Et_w.png" /><figcaption>“docs” folder populated — Image by author</figcaption></figure><p>You can ignore those whose name starts with an _underscore: they contain the built, compiled version of your documentation. You should not push them on Github.</p><h4>3. Edit the config.py file</h4><p>The configuration file is important: If your documentation doesn’t work, if you have errors when you try to build your site, it’s most likely due to an error in the “<em>conf.py</em>”file. Here’s how you need to modify it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7150fee6b43cef41505c84aa90413f6/href">https://medium.com/media/d7150fee6b43cef41505c84aa90413f6/href</a></iframe><p>On this example file, I have deliberately deleted all the comments, except the main titles so that you can situate yourself.</p><p>In the “<em>Path Setup</em>” section, copy the three lines. <strong>Pay particular attention to <em>line 4</em></strong> which tells Sphinx that the root of the project is not the “<em>docs</em>” folder, but the parent folder!</p><p>In “<em>General configuration</em>”, three extensions are added. The first one allows to use the markdown in Sphinx. And the following ones allows Sphinx to generate documentation from the docstring of your functions.</p><p>Finally, in the “<em>Options for HTML output</em>” section, the Sphinx theme is replaced by “<em>sphinx_rtd_theme</em>”, which is the most commonly used theme for Python documentation websites.</p><h4>4. Install the missing dependencies</h4><p>If this is the first time you are using Spinx, you need to install the dependencies we just specified in the configuration file. Type the following commands:</p><pre>pip install recommonmark<br>pip install sphinx_rtd_theme</pre><h4>5. Build your doc</h4><p>It’s time to generate the HTML pages for your future documentation site. Make sure you are in the “<em>docs</em>” folder, and type the following command:</p><pre>make html</pre><p>You will then see this nice message appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/477/1*PWKEkPP0DpYJgEJZqEofvw.png" /><figcaption>Sphinx build succeeded — Image by author</figcaption></figure><p>Congratulation, your Shpinx’s installation is working properly. You can preview your site by opening the “<em>index.html</em>” file, which can be found in “<em>docs/_build/html</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mtm0CwT4Fkf6E5fxN64Nmw.png" /><figcaption>All Sphinx components connected — Photo by <a href="https://unsplash.com/@purzlbaum?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">🇨🇭 Claudio Schwarz | @purzlbaum</a> on <a href="https://unsplash.com/s/photos/cables-connected?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Generate documentation from your code</h3><p>You have probably noticed that the site you just generated is empty: the documentation of your functions is missing! So let’s see now how to automatically create documentation from specifications (docstings) of your code.</p><h4>1. Create the folder tree</h4><p>In the “<em>docs</em>” folder, create a sub-folder “<em>source</em>”, then two other sub-folders “<em>api</em>” and “<em>examples</em>”. Like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*NszgmjssSX6Z6zjEW4UUFA.png" /><figcaption>“api” and “examples” folders — Image by author</figcaption></figure><p>We will put there all the documentation files specific to your project, that we are going to create now.</p><h4>2. Link the website to your code</h4><p>In the “<em>api</em>” folder, create a “<em>multiplication.rst</em>” file. The “<em>.rst</em>” files (aka reStructuredText) are an alternative to the “<em>.md</em>” (aka Markdown), supported by Sphinx.</p><p>And can will copy the following lines:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46c73a6fac48626049702d72705b9828/href">https://medium.com/media/46c73a6fac48626049702d72705b9828/href</a></iframe><p>This file allows you to retrieve the docstring from the Multiplication class, to to generate automatically a webpage with documentation.</p><p>It will be executed every time you push your code on Github, so that the site is always up to date with your code!</p><h4>3. Add an entry to the navigation tab</h4><p>Your beautiful class and its doc must be accessible by the user. Add an entry in the site menu that leads to the newly created page, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/378102c8972fa83539867fe37bdc96f1/href">https://medium.com/media/378102c8972fa83539867fe37bdc96f1/href</a></iframe><p>Pay attention to the “<em>source/api/multiplication</em>” line we added. This is the path to the previously created “<em>multiplication.rst</em>” file, without the extension.</p><h4>About the navigation menu</h4><p>You can create as many sections as you want in your menu by copying the following code. For example, you can create later another menu “Examples”, or “Getting started”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d452bddcd70b8e80843d370908549fa/href">https://medium.com/media/9d452bddcd70b8e80843d370908549fa/href</a></iframe><p>On Sphinx, a section of the menu begins with “toctree”.</p><p>The “maxdepth” parameter defines the depth of subtitle display.</p><p>And finally, “caption” is simply the name given to your section.</p><h4>4. Build your doc</h4><p>Re-generate the HTML files for your site. Type the following command from the “<em>docs</em>” folder:</p><pre>make html</pre><p>Then open the file “<em>docs/_build/html/index.html</em>” in your browser. Your documentation is created!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mxWVLknuFqWNHq1EXafI0w.png" /><figcaption>The references of you Multiplication class, generated from you code — Image by author</figcaption></figure><h3>Hosting on ReadTheDocs</h3><p><a href="https://readthedocs.org/">ReadTheDocs.org</a> is a service allowing you to build and host your documentation for free. Many popular libraries use it, such as <a href="https://rasterio.readthedocs.io/en/latest/">Rasterio</a>, <a href="https://docs.scrapy.org/en/latest/">Scrapy</a> or <a href="https://requests.readthedocs.io/en/master/">Requests</a>.</p><p>During this last step, we will host the site previously created on ReadTheDocs. So, go on and <a href="https://readthedocs.org/">create an account on it</a>.</p><h4>1. Add a .readthedocs.yml file</h4><p>You will add again another configuration file to the root of your project, named “<em>.readthedocs.yml</em>”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7170ce07fb490282f160faecf95d8ff/href">https://medium.com/media/a7170ce07fb490282f160faecf95d8ff/href</a></iframe><p>The purpose of this file is to tell ReadTheDocs how to build your documentation.</p><p>For this, <em>line 9 and 10</em>, it is told to use Sphinx, with the path to the configuration file.</p><p><em>Line 13</em> tells ReadTheDocs to create a PDF version of the site.</p><p>And finally, on <em>lines 17 to 19</em>, it is told to install the dependencies of your library, so that it can run it to retrieve your docstring.</p><h4>2. Import your repository</h4><p>Go to your ReadTheDocs dashboard, by clicking on the “<em>My project</em>” tab of your profile. Then press “<em>Import a project</em>”, as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*ndU-XZQCZ3biJkPATDlZKg.png" /><figcaption>“<strong>Import a Project</strong>” button on ReadTheDocs dashboard — Image by author</figcaption></figure><p>Find the repository of your library, and import it by pressing the “+”.</p><p>Then, specify the name of your project (e.g. “<em>medium-multiply</em>”). It will be used to generate the URL of your site (“<em>medium-multiply.readthedocs.io</em>”). And finally click on “<em>Next</em>”.</p><h4>3. Push to Github</h4><p>You will now push the changes to your project on Github. Make sure to commit the “<em>.readthedocs.yml</em>” file. For the “<em>docs</em>” folder, make sure you send only the files and folders highlighted in blue in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*MlJLLlGRE9xYaYzbPO8RCA.png" /><figcaption>Files and folders to push from “docs” — Image by author</figcaption></figure><p><strong>Reminder:</strong> folders starting with an underscore should not be pushed on Github. ReadTheDocs will build its own version of your documentation.</p><h4>That’s it!</h4><p>Wait a few seconds while ReadTheDocs recovers your files and builds your site. Refresh the “<em>Build</em>” page of your project until you see “<em>Passed</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*93oQEBQBILmHYOaWzvcUZQ.png" /><figcaption>The build passed on ReadTheDocs — Image by author</figcaption></figure><p>And that’s it! You can visit your library’s website by clicking on the green “<em>View doc</em>” button. You can also consult the website of the library we just created during this article: <a href="https://medium-multiply.readthedocs.io/en/latest/">medium-multiply.readthedocs.io</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3bg1QPRSvOuvL9qfIq7grQ.png" /><figcaption>Deep dive completed — Photo by <a href="https://unsplash.com/@carolinehdz?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Caroline Hernandez</a> on <a href="https://unsplash.com/backgrounds/art/aquarium?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Your deep dive is now completed!</p><p>You’ve just learned how to create a solid library with tests; How to set up a pipeline to quickly deploy your updates; And how to easily publish a website with up-to-date documentation.</p><p>Don’t hesitate to fork <a href="https://github.com/Joffreybvn/medium-multiply">the repository of the “medium-multiply” library</a>, created especially for this article.</p><p>Thanks for reading! Any feedback is welcomed, you can reach me out here in the comments, or on Twitter: <a href="https://twitter.com/Joffreybvn">Joffreybvn</a>. And stay tuned for more beginner-friendly guides.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7f618719e14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/deep-dive-create-and-publish-your-first-python-library-f7f618719e14">Deep dive: Create and publish your first Python library</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>