<?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[Arthur Engineering - Medium]]></title>
        <description><![CDATA[Shining a light into the black box of AI. One commit at a time. - Medium]]></description>
        <link>https://medium.com/arthur-engineering?source=rss----4a43c2f1244---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Arthur Engineering - Medium</title>
            <link>https://medium.com/arthur-engineering?source=rss----4a43c2f1244---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 01:19:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/arthur-engineering" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Picking A Kubernetes Orchestrator: Airflow, Argo, and Prefect]]></title>
            <link>https://medium.com/arthur-engineering/picking-a-kubernetes-orchestrator-airflow-argo-and-prefect-83539ecc69b?source=rss----4a43c2f1244---4</link>
            <guid isPermaLink="false">https://medium.com/p/83539ecc69b</guid>
            <category><![CDATA[prefect]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[orchestration]]></category>
            <category><![CDATA[argo]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Ian McGraw]]></dc:creator>
            <pubDate>Tue, 15 Dec 2020 16:48:21 GMT</pubDate>
            <atom:updated>2020-12-15T16:48:20.880Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bug4XKU4n4dLb9kD" /><figcaption>Photo by <a href="https://unsplash.com/@larisabirta?utm_source=medium&amp;utm_medium=referral">Larisa Birta</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Over the summer, Arthur has been hard at work building our new microservice-based platform. The new platform is a complete overhaul of the Arthur product that includes new Golang based services, a state of the art OLAP database, a revamped UI and stream-based inference enrichments (more on the new platform in an upcoming blog post). Today we are going to focus on inference enrichments, which are a powerful feature that allow customers to add insights such as explanations, anomaly detection, and bias mitigation to their inferences. With each enrichment the customer enables, the platform will add one or more properties to every inference as it arrives. For example, anomaly detection adds an anomaly_score column to every inference, which can be used to trigger alerts and help with investigations in the Arthur UI. Under the hood, each of these enrichments are separate machine learning pipelines trained per customer model. This workflow shows a simplified version of what these pipelines look like:</p><figure><img alt="High level inference enrichment architecture" src="https://cdn-images-1.medium.com/max/639/1*6TAVoorQ6R84yAbAI4et4g.jpeg" /><figcaption>High level inference enrichment architecture</figcaption></figure><p>Orchestrating and monitoring all of the enrichment machine learning pipelines proved to be a significant challenge, especially since customers can turn enrichments on and off on demand. To complicate things further, Arthur supports a “deploy anywhere installation” that customers can use to run the product in a private network. This meant our orchestration solution also needed to be self-contained, easy to standup, and have a low resource overhead. During our platform rebuild, we faced an important decision. Which of the open-source orchestration tools could support our needs?</p><p>We evaluated a handful of workflow orchestrators in our search. But for brevity, I will only discuss the most competitive contenders: Airflow, the most popular Python-based framework, Argo, a Kubernetes-native workflow orchestrator, and Prefect, a Python-based newcomer with some advanced workflow semantics.</p><h4>Airflow, Argo, and Prefect</h4><p>Before diving into the tools, I will preface that this post is intended for readers with some knowledge of the problems workflow orchestrators solve. If you’re new to any of the tools and looking to brush up, here are a few sections I thought were good introductions to each:</p><p><strong>Airflow:</strong> I recommend starting with their <a href="https://airflow.apache.org/docs/stable/">docs</a> and specifically, the <a href="https://airflow.apache.org/docs/stable/concepts.html">concepts</a> section. <br><strong>Argo:</strong> Argo’s <a href="https://argoproj.github.io/argo/">docs</a> are a bit on the lighter side but their <a href="https://argoproj.github.io/argo/workflow-concepts/">concepts</a> section is a helpful starting point. They also have an active <a href="https://argoproj.github.io/community/join-slack">Slack community</a>.<br><strong>Prefect: </strong>Prefect has thorough <a href="https://docs.prefect.io/">docs</a> but it is confusingly split into two sections. The <a href="https://docs.prefect.io/core/">core</a> section describes the workflow execution and definition language. The <a href="https://docs.prefect.io/orchestration/">orchestration</a> section describes the Prefect server and scheduling. Prefect also has an active <a href="https://prefect-slackin.herokuapp.com/">Slack community</a>.</p><p>Ok now diving in…</p><p>This table is an extensive comparison of all the features we looked at between the tools. For a walk-through of the highlights, see the description below the table.</p><figure><img alt="Orchestration tools side-by-side comparison" src="https://cdn-images-1.medium.com/max/1024/1*YEHJKv0b5whNVB-mPfZT_w.png" /><figcaption>Orchestration tools side-by-side comparison</figcaption></figure><p>With any tool bake-off, it’s important to understand what it can do well, and where it lacks important features. In the case of Airflow, it got many features right that have established it as the community favorite:</p><ol><li>Fault-tolerant scheduling and running time aware jobs</li><li>Python based DAG definition</li><li>Built-in library of operators</li></ol><p>On the flip side, Airflow’s design choices give it some distinct drawbacks:</p><ol><li>No dynamic workflows</li><li>No parameterized workflows</li><li>Minimal rest API</li><li>Hard to run containerized workflows with Kubernetes</li></ol><p>*Note, Airflow 2.0 is on the horizon and may alleviate some of these pain points, see <a href="https://www.astronomer.io/blog/introducing-airflow-2-0/">here</a> for the latest.</p><p>Compared to Airflow, Argo is a relatively newer project (7k stars on Github vs Airflow’s 19.4k), but already has a large community following. It is currently a Cloud Native Computing Foundation incubating project and has an ecosystem of related tools such as ArgoCD, Argo Rollouts and Argo Events. Argo’s slogan is to “get stuff done with Kubernetes” and has some important features to back up that claim:</p><ol><li>Running containers</li><li>Highly parallel</li><li>Low-latency scheduler</li><li>Can pass data and artifacts between steps</li><li>Dynamic DAGs</li><li>Interacting with Kubernetes resources</li><li>Kubernetes native state storage</li><li>Easy to deploy</li><li>Event-based ecosystem</li></ol><p>Clearly, Argo is all-in on Kubernetes, which means it falls short for a number of use cases:</p><ol><li>No operators</li><li>No easy way to execute Python functions directly</li><li>YAML Workflow definition</li><li>Requires Kubernetes</li><li>Not fault-tolerant scheduling</li></ol><p>Lastly Prefect, which is the newest member of the three (5.5k stars on Github), combines some of the best of both Airflow and Argo:</p><ol><li>Highly available scheduler</li><li>Lightweight Python-based DAG definition language</li><li>Dynamic DAGs</li><li>Running containers</li><li>Built-in library of operators</li></ol><p>Even though Prefect has a lot of the best features of both Airflow and Argo, there are some limitations:</p><ol><li>No open source Kubernetes deployment</li><li>Made up of a complex group of services</li><li>Must execute workflow definitions to register them</li></ol><h4>Making the Right Decision for Arthur</h4><p>Airflow and Prefect both do a lot of things well. Airflow outshines both Argo and Prefect for uses cases in non-containerized environments with strict, fault-tolerant execution schedules. With the upcoming release of Airflow 2.0 and improved Kubernetes integrations, it will be better equipped to compete with Argo in containerized environments. On the other hand, Prefect’s DAG definition language is very well designed and intuitive to insert into existing code. Had our use case not required a lightweight tool or been fully containerized, Airflow or Prefect likely would have been our choice. In the end, we chose Argo because it is container-first, lightweight and has out of the box Golang clients.</p><p>Being container-first was the most important factor because we run our platform entirely in Kubernetes, so our jobs were already containerized. We needed a workflow orchestrator that excelled at running and managing containers, and Argo was the best tool we found. It has out of the box support for almost any Kubernetes container setting you could ask for. We were able to configure Service Accounts for dynamic Spark clusters (more on these in a later post), Annotations for Kube2IAM AWS access, environment variable mounts from Secrets as well as options for init containers and sidecars easily. In the future we look forward to trying out Argo’s <a href="https://argoproj.github.io/argo/examples/#daemon-containers">Daemon Containers</a> that let you spin up long-lived services to use throughout the workflow.</p><p>Second to being container-first, Argo’s small footprint was a huge bonus for the tool. The core workflow functionality is implemented in a single pod and has an optional UI that requires a secondary pod. Since we package and ship our platform to customers’ VPCs, minimizing the number of pods is a must. Running Airflow with a similar setup required a web server, scheduler, a handful of workers each with sidecars, and a database. Similarly, Prefect has a database, GraphQL API, management services, agents, and flow storage processes. Argo allows us to accomplish more with a significantly smaller footprint than the other tools.</p><p>Lastly, one of the more powerful features when using Argo and Go-based applications is the ability to use the open-source <a href="https://github.com/argoproj/argo/blob/master/pkg/client/clientset/versioned/typed/workflow/v1alpha1/workflow_client.go#L21">Argo Golang Kubernetes</a> client (Note this isn’t specific to Go, someone could implement a client in any language). The client is the same client Argo uses internally to edit and respond to Workflow objects submitted to Kubernetes. As a result, our application-layer can dynamically define <a href="https://github.com/argoproj/argo/blob/master/pkg/apis/workflow/v1alpha1/workflow_types.go#L97">Workflow structs</a> and submit them on the fly. This allows us to move a lot of the complex logic out of our workflow into the application code. As an example, in the Arthur platform customers can toggle enrichments for their model and the backend will train a model for each enabled enrichment. Normally with a static, predefined workflow, we would need to write logic into the DAG to handle every possible combination of customer-enabled features, so the DAG can work for all customers. With Argo and the Kubernetes client, we can instead construct the DAG dynamically as a function of the customer’s chosen enrichments. This allows us to submit unique workflows for each customer, even across different invocations of the same customer’s workflow over time. See <a href="https://github.com/argoproj/argo/blob/master/examples/example-golang/main.go">here</a> for an example setting up and submitting a workflow with the Go Argo Kubernetes client.</p><h4>TLDR</h4><p>Argo is a powerful Kubernetes workflow orchestration tool. It is container-first, lightweight, and easy to integrate with external systems, especially Go-based services. Although seemingly minor, the ability to construct workflows programmatically and specific to each customer has been a huge win for our platform. We have already begun building our machine learning pipelines using this method. The pipelines are event-driven, tailor-built to each customer, and fully handle training, saving, building, deploying, and configuring dynamic pipelines on demand. In the short few weeks we’ve had Argo running in our platform, its power and flexibility has excited our team and streamlined our machine learning orchestration. We’re looking forward to seeing what features we can build next with Argo.</p><p>Keep an eye out for some more Argo tips and tricks in following blog posts!</p><p>Additional Reading:<br><a href="https://argoproj.github.io/">https://argoproj.github.io</a><br><a href="https://airflow.apache.org/docs/stable/">https://airflow.apache.org/docs/stable/</a><br><a href="https://medium.com/the-prefect-blog/why-not-airflow-4cfa423299c4">https://medium.com/the-prefect-blog/why-not-airflow-4cfa423299c4</a> <br><a href="https://www.astronomer.io/blog/introducing-airflow-2-0/">https://www.astronomer.io/blog/introducing-airflow-2-0/</a><br><a href="https://docs.prefect.io/">https://docs.prefect.io</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83539ecc69b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arthur-engineering/picking-a-kubernetes-orchestrator-airflow-argo-and-prefect-83539ecc69b">Picking A Kubernetes Orchestrator: Airflow, Argo, and Prefect</a> was originally published in <a href="https://medium.com/arthur-engineering">Arthur Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Monolith to Microservices]]></title>
            <link>https://medium.com/arthur-engineering/from-monolith-to-microservices-fed2fe56478c?source=rss----4a43c2f1244---4</link>
            <guid isPermaLink="false">https://medium.com/p/fed2fe56478c</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Kelsey Kerr]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 20:32:19 GMT</pubDate>
            <atom:updated>2020-12-11T21:05:42.597Z</atom:updated>
            <content:encoded><![CDATA[<p>Speed is the name of the game at startups. At Arthur, we’re moving fast and iterating quickly to build the best model monitoring platform on the market, and that’s why we embarked on the journey to migrate our original monolith into microservices. In the early days of Arthur, when the market was nascent and the engineering team consisted of just a couple of people (and the CEO putting on his developer hat), a monolith made sense. Starting with microservices would have added additional complexity, would have gone against the <a href="https://martinfowler.com/bliki/Yagni.html">YAGNI</a> mindset, and likely would have slowed the small, but mighty team down.<br> <br><em>“Don’t be afraid of building a monolith that you will discard, particularly if a monolith can get you to market quickly.”</em> — Martin Fowler <br> <br>As 2020 rolled on, the market for Arthur’s product opened up, the engineering team more than doubled in size, and we were faced with a tough question: do we continue on with the monolith knowing that we are likely punting on scaling issues, or do we take the time to slow down now and rethink our architecture in order to speed up later?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T-QIOcuEQ1YsXHifuq-v7A.png" /><figcaption>simplified Arthur architecture from the early days</figcaption></figure><h3><strong>How we knew it was time to make the switch</strong></h3><p>As the title suggests, we decided that it was time to invest in an ecosystem of microservices. It was clear that we had achieved product market fit and we would have to scale to fit the demands of multiple clients and that our internal development speed would likely benefit from decoupled services. For example, we had great test coverage for our monolith, but the service was so big that our very thorough unit and integration tests would take over 20 minutes to run if we weren’t running them in parallel. We also knew that a highly available platform was non-negotiable, but with a monolith, that meant scaling up to meet the demand of a couple of our frequently hit data ingestion endpoints while the majority of endpoints had a fraction of the throughput and memory usage. Other motivating factors for switching to microservices were the ability to better parallelize work amongst the team and make it quicker and easier to add/edit/remove features. We were confident that microservices were the way to go, however we knew that it would be a large undertaking and that there was the infamous Microservice Premium.</p><h3><strong>How we got started with microservices</strong></h3><p>We started with just a few microservices, as we read that knowing when to create a new microservice is as much of an art as it is a science. With this in mind, we erred on the side of caution and only split out the obvious pieces first. We decided to keep our user, authentication, model metadata, alerts, and tenant management logic in a service and split out the following pieces into separate microservices:</p><ul><li>inference ingestion</li><li>inference &amp; metric retrieval</li></ul><p>Inference ingestion was an obvious candidate for a new service because it could be easily decoupled from the rest of the platform, and it was something that we knew would have to scale horizontally to meet customer data load. We designed inference ingestion as a lightweight service that makes use of Kafka to ingest both streaming data and batch data. From here, it naturally made sense to create an additional service that was responsible for retrieving inferences and calculating metrics on these inferences. It was important to consider performance here and we knew that our choice of data store was crucial to our ability to serve up insights quickly. With this in mind, we were able to leverage the expertise of our data engineers to choose the right data store for our inferences and write the microservice that was responsible for retrieving inferences and calculating metrics. While our data engineers worked to build these microservices, the remaining backend engineers began tackling API design and the remaining product work. After designing our APIs and getting through the implementation of the user, authentication, metadata, alerts, and tenant management, it became evident that the alerting part of our platform was a good candidate for its own microservice. Below you’ll find a simplified diagram of the architecture we arrived at.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tAar4hEl2gUXsvu0TGOt7g.png" /><figcaption>simplified current Arthur architecture</figcaption></figure><h3><strong>A good excuse to rethink some other things</strong></h3><p>Knowing that we were going to have to invest a lot of time into our new architecture, we also saw this as an opportunity to reflect on other decisions — particularly our backend language. Our monolith was written in Python, as it is the language of data science and machine learning, and it’s one of the most beloved languages among software developers. For these reasons, Arthur will always have some parts of our product written in Python, like our SDK. Internally, we still love Python, but we had some performance and scaling concerns with our Gunicorn + Flask app and we felt a strongly typed language better lent itself to our API first approach. Being a cutting edge startup, we decided to use Java! ……kidding, of course. While I’m a Java fan, it’s widely known that many developers, especially those who are inclined to work at startups, dislike the language. Java did check a couple of our boxes in that it’s strongly typed and fast. Knowing that we wanted these things but also wanted to use a language that developers are excited about, we decided to use Go, as it is incredibly fast, well liked within the developer community, and Go routines are baller.<br> <br>The beginning of the journey was pretty arduous. Transitioning from a monolith to microservices is hard enough, but we also had to get used to using Go. Many of us came from object-oriented backgrounds, so we felt a little lonely without classes and inheritance and often wondered why the heck there wasn’t a ternary operator. After some wrestling with pointers and error handling, we did start to see the light of day and noticed that we were cranking out new endpoints and features quickly, our tests were incredibly fast and Go routines made concurrency a breeze. While we have embraced Go, we also recognize that the ability to choose the right language for the job is one of the reasons we chose microservices, so that may mean we adopt other languages in the future.</p><h3><strong>It wasn’t easy, but it was worth it.</strong></h3><p>Along this journey, we definitely experienced some of the pain points that come with adopting microservices. It was clear from the beginning that we’d be introducing additional complexity to our DevOps processes and we’d need to figure out how to create pipelines that would allow us to independently deploy each microservice. This required everyone to quickly get ramped up with Kubernetes and within a couple of months everyone had experience updating Helm Charts and deploying new services. Some of the other pain points we ran into were issues with observability, logging, and being able to test services independently from each other. We responded to these by improving our logging, both in the log content and the log accessibility via Kibana, and writing our external client interfaces in a way that allowed us to add mock clients that can be used when running and testing the services locally. We continue to encourage developers to speak up about pain points and areas for improvement. <br> <br>While the big task of breaking up our monolith into microservices is behind us, we know that the process of constant improvement and iteration will continue. So far we’ve already seen how microservices allow us to scale both the platform and the team by allowing us to scale services independently and making it easy to parallelize development work. We’re proud of the architecture investments we’ve made and we’re confident that the platform will allow us to grow and scale to meet Arthur’s growth. The things that we love about microservices are also the things we love about the engineering culture at Arthur — we’re able to move fast and iterate quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fed2fe56478c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arthur-engineering/from-monolith-to-microservices-fed2fe56478c">From Monolith to Microservices</a> was originally published in <a href="https://medium.com/arthur-engineering">Arthur Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Best Practices for creating a user-friendly Python SDK]]></title>
            <link>https://medium.com/arthur-engineering/best-practices-for-creating-a-user-friendly-python-sdk-e6574745472a?source=rss----4a43c2f1244---4</link>
            <guid isPermaLink="false">https://medium.com/p/e6574745472a</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[engineering]]></category>
            <dc:creator><![CDATA[Harrison Linowes]]></dc:creator>
            <pubDate>Fri, 11 Dec 2020 20:30:16 GMT</pubDate>
            <atom:updated>2020-12-11T20:30:16.460Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LpBEgFjOtDgYa6VLWzNKjA.jpeg" /><figcaption>Our SDK really gets data scientists excited… no matter what operating system they use</figcaption></figure><h3>How to build a user-friendly Python SDK</h3><p>No matter how well designed and implemented an application may be, if the user experience sucks, the application won’t be effective. Dashboard and monitoring products in particular are often marketed and designed for different end users: analysts, business leaders, software engineers. Each user may have a different preferred interface to use the application. Analysts may often use a GUI while a data scientist may use an API or SDK. The challenge is often designing the best user experience across all of these different user interfaces.</p><p>At Arthur we’ve taken an API-first approach when designing and building our model monitoring platform. The API exposes functionality to allow customers to manage their machine learning models, send inferences as they are computed, and retrieve information related to the performance of their model. Most data scientists prefer to interact with our platform through our Python SDK, which eventually communicates with our REST API. Our SDK seamlessly integrates with model pipelines, which often are in the form of Jupyter Notebooks. As we’ve built out this functionality we’ve learned a lot about best practices and techniques for creating an SDK. Here’s what we’ve done to build a user-friendly SDK:</p><h3>Create Clear Function and Class Import Paths</h3><p>Pathing became a large focus as we were designing our SDK. We want to ensure that users can anticipate the location of utility functions, core SDK classes, and constants they may need to use throughout development. Logical pathing also can be helpful when using autocomplete in IDEs. We determined four main packages that all modules will live under.</p><ol><li><em>Client</em>, handles HTTP communication with our REST API</li><li><em>Common</em>, contains constants and exceptions that may be referenced or used in other pieces of the SDK</li><li><em>Core</em>, contains all core classes that are used to interact with our application (ArthurModel and ArthurAttribute)</li><li><em>Explainability</em>, contains model explainability specific code</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*l6urTaoAuAvEJ8euxu_sJw.png" /><figcaption>SDK folder structure</figcaption></figure><p>While organizing code logically can make it easier for users to find import paths, we generally will create shortcuts for commonly used objects. The easiest way to do this is to import a module in a root package __init__.py file. For example, since the ArthurModel is located in arthurai.core.model.ArthurModel we created a shortcut by importing it directly to the arthurai package. This simplifies the syntax to from arthurai import ArthurModel. Logically organizing our code not only makes it easier for users to interface with the SDK, but also helps organize the documentation intuitively.</p><h3>Provide Thorough Documentation</h3><p>Code documentation is a vital part in ensuring we create an easy to use SDK. We use RestructuredText and Sphinx to auto-generate user documentation. <a href="https://www.python.org/dev/peps/pep-0287/">ReStructuredText</a> is a plaintext markup syntax which can be used in Python function and class inline documentation. <a href="https://www.sphinx-doc.org/en/master/index.html">Sphinx</a> is a framework which can auto-generate documentation from reStructuredText and export it to multiple formats including HTML. Sphinx is often used to generate Python library documentation and while reStructuredText is the recommended markup syntax for Python documentation (<a href="https://www.python.org/dev/peps/pep-0287/">PEP 287</a>), there are three markup syntax options that most developers will use:</p><h4><a href="https://www.python.org/dev/peps/pep-0287/">ReStructuredText</a></h4><pre>def foobar(arg1: int, agr2: str) -&gt; bool:<br>    &quot;&quot;&quot;Function summary<br>    <br>    :param int arg1: Description of arg1<br>    :param str arg2: Description of arg2<br>    :return: Boolean determining fooness of the bar<br>    <br>    :example:<br>    <br>    &gt;&gt;&gt; result = foobar(1, &quot;hello&quot;)<br>    &quot;&quot;&quot;<br>   <br>    return True</pre><h4><a href="https://google.github.io/styleguide/pyguide.html">Google-style</a></h4><pre>def foobar(arg1: int, agr2: str) -&gt; bool:<br>    &quot;&quot;&quot;Function summary<br>    <br>    Args:<br>        arg1 (int): Description of arg1<br>        arg2 (str): Description of arg2<br>        <br>    Retruns: <br>        bool: determining fooness of the bar<br>    <br>    Examples:<br>    <br>        &gt;&gt;&gt; result = foobar(1, &quot;hello&quot;)<br>        &gt;&gt;&gt; print(result)<br>         True<br>    &quot;&quot;&quot;<br>   <br>    return True</pre><h4><a href="https://numpydoc.readthedocs.io/en/latest/format.html">Numpy-style</a></h4><pre>def foobar(arg1: int, agr2: str) -&gt; bool:<br>    &quot;&quot;&quot;Function summary<br>    <br>    <strong>Parameters</strong><br><strong>    ----------</strong><br>        arg1: int<br>            Description of arg1<br>        arg2: str<br>            Description of arg2<br>        <br>    <strong>Returns</strong><br><strong>    -------</strong> <br>        bool: determining fooness of the bar<br>    <br>    <strong>Examples<br>    --------</strong><br>    &gt;&gt;&gt; result = foobar(1, &quot;hello&quot;)<br>    &gt;&gt;&gt; print(result)<br>    True<br>    &quot;&quot;&quot;<br>   <br>    return True</pre><p>There are pros and cons to each style and a decision on which to use in your library often comes down to personal preference. We chose to use reSructuredText because of its easy integration with Sphinx and some of our developers familiarity with it. As I mentioned Sphinx supports reStructuredText out of the box, but a plugin called <a href="https://www.sphinx-doc.org/en/master/usage/extensions/napoleon.html">Napoleon</a> can be used to add Google and NumPy style support.</p><h3>Set Clear Function Design Conventions</h3><p>While most of the basic functionality of our application is integrated into our SDK, to ensure nimble and clean future development we outline 8 guidelines which our engineers use when creating new functionality.</p><ol><li>Determine what package/module new code/functions should live under, or in rare cases, whether a new package or module should be created.</li><li>Do not use static methods (@staticmethod) for client facing functions; instead, use module level functions. If a function is not associated with an instance of a class, and is a utility function, it is more clear to associate the function with a module.</li><li>Do not use simple getter and setter functions. Use Python @property tags instead. In addition to being more pythonic, this maintains a syntax similar to directly accessing attributes but allows more control over how the attributes are retrieved and manipulated.</li><li>A function’s action should be represented by its name.</li><li>Try to not hide function operations from clients. For example, if a function significantly transforms its input before storing or sending it to the API then consider creating and exposing a helper function for the client to use. Ensure documentation and error handling is properly updated to guide clients to use this helper function.</li><li>Create functions which do specific operations rather than generic functions with optional parameters. If clients use incorrect function, exceptions should direct them toward the correct function for their use-case.</li><li>Specify function parameters and generally avoid *kwargs.</li><li>Functions which do similar operation should have similar names. In addition, similar parameters should be in the same order with unique parameters appended at the end.</li></ol><h3>Give Clear Explanation of Exceptions and Error Handling</h3><p>Many SDK functions will interact with backend microservices or utilize code from 3rd party libraries, any of which could throw an exception. This increases the importance of error handling to ensure users can understand issues and guide themselves to a solution.<br> <br>Within our SDK, we use custom exceptions to handle errors that occur. Inspired by Python’s hierarchical organization of exceptions (<a href="https://airbrake.io/blog/python-exception-handling/class-hierarchy">Python Exception Hierarchy</a>), we have taken a similar approach to ensure development is smooth and error messages are clear. At the top of the tree is a Base Exception class which contains helper functions and standardizes our error message format.<br> <br>Most function calls within our SDK contain a HTTP call to our REST API. API calls generally return errors through HTTP response codes. However, to add extra functionality and convenience in our SDK, we may add additional error handling to our REST calls. To do this we handle all HTTP responses within the SDK functions and not within our HTTP Client package. This allows us to customize API response handling within the context of each SDK function. For example, when calling ArthurModel.save() we hit a POST endpoint on our API by calling the SDK HTTP client package (client.post()). Instead of handling any model save errors within the client.post() method we will pass them through to the ArthurModel._save_model_post() function which initiates the call.<br> <br> Exceptions handled in HTTP Client:</p><pre>def _save_model_post(self, model):<br>    &quot;&quot;&quot;Saves a model object by sending a POST request to the API&quot;&quot;&quot;</pre><pre>    # if REST call errors are handled in the http_client <br>    # function it will not have access to model <br>    # atttritbutes and functions<br>    response = self.http_client.post(self.to_json())<br>    return True</pre><p>Exceptions handled in SDK functions, allows for more module error handling:</p><pre>import ATTRIBUTE_ERROR</pre><pre>def _save_model_post(self, model):<br>    &quot;&quot;&quot;Saves a model object by sending a POST request to the API&quot;&quot;&quot;</pre><pre>response = self.http_client.post(self.to_json())</pre><pre>if response.status_code == 400 and<br>     ATTRIBUTE_ERROR in response.json():</pre><pre>      # retrieves the name of the attribute from the response <br>      # message<br>      attribute_name = response.body() \<br>        [response.body().find(&quot;:&quot;)+1:]</pre><pre>      raise Exception(&quot;Error saving model due to &quot; + <br>        f&quot;invalid attribute: {model.get_attribute(attribute_name)}&quot;)</pre><pre>return True</pre><p>Our SDK utilizes a handful of third party libraries which may throw their own exceptions. Another principle we take when using 3rd party packages is to catch exceptions and wrap those errors in our own messaging. This is done to help avoid confusion and give more context to unintended errors.</p><h3>Testing Everything. Twice.</h3><p>Testing a customer facing tool is vital. Our test suite primarily consists of unit tests which ensure the functionality of each function call within the SDK. SDK’s in general are often used by clients in various configured environments. For Python SDK’s this means different versions of Python and of existing libraries. Another aspect of an evolving application is ensuring backwards compatibility. Building and maintaining an expansive test suite can help ensure the library will work as intended in all of these situations.</p><h4>Separate the Test Package</h4><p>To simplify the structure and minimize the size of our SDK, we’ve separated the testing package from our SDK bundle. Since our testing package is separate, it is organized in the same manner as our SDK package. For example in our SDK the ArthurModel class is located at arthurai.core.models therefore the tests for ArthurModel are located in tests.core.models.</p><h4>Mock HTTP Client Functions</h4><p>Within the ArthurAI library we built our own custom wrapper to Python’s request library. The main advantage to this structure is so we can abstract all REST specific functionality to its own package within our library. While it is possible to mock the request library (we’ve used <a href="https://requests-mock.readthedocs.io/en/latest/">request-mock</a> in the past) the structure we use also makes it easy to mock functions which make HTTP calls instead of dealing with the requests library directly.</p><h4>Testing CI/CD</h4><p>Before every PR is merged into our master branch we run a set of tests to ensure that each commit does not introduce new bugs into our library. For our testing suite we use <a href="https://docs.pytest.org/en/stable/">Pytest</a>. However in order to confirm that our library continues to be compatible with all supported Python versions we run our tests using a tool called <a href="https://tox.readthedocs.io/en/latest/">Tox</a>. Tox provides the ability to run the SDK test suite within different environments making it easy to test the code across different dependencies and versions of Python. In addition to running our test suite, we also run a linter to enforce code styling, conventions, and typing. We use a tool called <a href="https://github.com/cloudmatrix/myppy/">MyPy</a> for this.</p><h3>Conclusion</h3><p>Throughout iterating on the design and implementation of our SDK we found it’s easy to create a library to interface with an API, but it’s difficult to determine how to do this in a scalable and intuitive way which prioritizes the needs of both the developer and end user. The guidelines discussed above have helped us maintain a clean repository of code, made it easy for our developers to add functionality, and created a seamless environment to test and document the ArthurAI Python SDK.</p><h4>Miscellaneous SDK Conventions &amp; Links</h4><ul><li><a href="https://www.python.org/dev/peps/pep-0008/">PEP 8 Style Guidelines</a></li><li>Python Typing and Type Hints (<a href="https://www.python.org/dev/peps/pep-0484/">PEP 484</a>)</li><li><a href="https://pypi.org/project/sphinx-autodoc-typehints/">Sphinx Integration</a></li><li><a href="https://packaging.python.org/guides/single-sourcing-package-version/">Single Source Versioning</a></li><li><a href="https://semver.org/">Semantic Versioning</a></li></ul><h4>Things that inspired us:</h4><ul><li><a href="https://www.python.org/dev/peps/pep-0020/">Zen of Python</a></li><li><a href="https://azure.github.io/azure-sdk/python_introduction.html">Azure Python SDK Guidelines</a></li><li><a href="https://www.python.org/dev/peps/pep-0008/">PEP 8 Conventions</a></li><li><a href="https://pandas.pydata.org/docs/reference/index.html">Pandas SDK Docs</a></li><li><a href="https://github.com/kubernetes-client/python/tree/master">K8S Python SDK</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6574745472a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/arthur-engineering/best-practices-for-creating-a-user-friendly-python-sdk-e6574745472a">Best Practices for creating a user-friendly Python SDK</a> was originally published in <a href="https://medium.com/arthur-engineering">Arthur Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>