<?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 Donatas Rasiukevicius on Medium]]></title>
        <description><![CDATA[Stories by Donatas Rasiukevicius on Medium]]></description>
        <link>https://medium.com/@d.rasiukevicius?source=rss-418f73904475------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*eaZiDTRxoiMZtwcn24naXA.png</url>
            <title>Stories by Donatas Rasiukevicius on Medium</title>
            <link>https://medium.com/@d.rasiukevicius?source=rss-418f73904475------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 22:09:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@d.rasiukevicius/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[Functional Programming in Django]]></title>
            <link>https://medium.com/lab-digital/functional-programming-in-django-96c47d4ca0ba?source=rss-418f73904475------2</link>
            <guid isPermaLink="false">https://medium.com/p/96c47d4ca0ba</guid>
            <category><![CDATA[django]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[application-design]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Donatas Rasiukevicius]]></dc:creator>
            <pubDate>Wed, 01 Jul 2020 08:51:55 GMT</pubDate>
            <atom:updated>2020-07-01T12:39:17.946Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZKgpU5QzgNKGxYj1hjJFA.png" /></figure><p>I’m a software engineer at <a href="https://labdigital.nl/en/">Lab Digital</a>. In this article I want to take a look at how to apply concepts from functional programming into everyday python/django programming.</p><p>Before I even became a software engineer, some of my friends were preaching about ‘Functional Programming’. It honestly seemed like a cult. Every single member of this cult was very well informed; they were smart, they knew a lot about programming, and they would gladly tell you why FP is the future of programming with infectious enthusiasm. They would give you a number of reasons for why FP is the only solution you ever really need.</p><ol><li>Complex problems like concurrency become trivial, you can use async everywhere without worry!</li><li>Because FP operates on this notion of pure functions, you will never have runtime errors!</li><li>It has lazy evaluation and function composition, which makes it extremely efficient in data transformation!</li><li>Thanks to its ‘high-level’ syntax it is also way more readable!</li></ol><p>But no matter which combination of benefits they would mention, they would always end on the same note: “Functional Programming has made me a better programmer”. That common sentiment is what I will focus on in this article. I hope to show you the non-technical superpowers you obtain from thinking from an FP point of view and how I incorporate them into my way of working without ever having to actually write in an FP style and violate django best practices.</p><h3>FP and Django</h3><p>While you <em>can</em> do FP in python, it is very clearly not designed for that. The standard library lacks compile-time optimizations and concepts like pattern-matching or proper type checking. This is a very clear design choice; Guido van Rossum (creator of Python) himself has once stated that he did not envision python as a functional language, so it isn’t one. Django very much builds on top of this design, embracing Object Oriented and Imperative paradigms. Take the CreateView for instance, a staple of class-based views (which are the django gold standard for view logic). It has 9 ancestors demonstrating some pretty nifty inheritance and dependency injection, a big no-no in FP. You could potentially write your django application with function based views, which are more akin to FP, but the reality is that nobody does this and 90% of all examples you will find online will be about class-based views. Concurrency, broadly speaking, is a non-issue in most django applications. The data transformations in web-development more often than not are relatively trivial, their complexity coming from dealing with state. So why then should you even care about FP as a django developer?</p><p>I argue that some really basic FP ideas make you really good at:</p><ol><li>factoring your code into small (easily testable) units</li><li>using (and abusing) the django ORM</li><li>interpreting user requirements</li><li>expressing the data flow of your application</li></ol><h3>Functions</h3><p>This will be the first article in the history of FP that does not talk about the citizenship status of functions, suffice it to say that functions are really important. What I think is more relevant for using FP in django is the idea of pure functions. These are functions that have no external dependencies. They operate on input and produce an output. They are completely deterministic and have no side-effects. fn = lambda x, y: x+ y is an example of a pure function. What I want to impose on you is that there is purity in almost every meaningful computation and identifying and isolating it makes your code simpler. In django you will often find yourself querying the database, then doing something with that data, and finally feeding it into a view to display it. The &#39;doing something with that data&#39; generally is where you will find your pure computation. Take the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd4452125e55b5569668abc402509492/href">https://medium.com/media/bd4452125e55b5569668abc402509492/href</a></iframe><p>There are many criticisms to be had over this code, but if you disregard some of its obvious flaws, I think it lends itself beautifully to showcase purity in an otherwise stateful transaction. Looking at this code we can see that the ingredient filtering can be completely deterministic. Given a list of ingredients and a list of ingredient names we should always produce the same set of ingredients.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/990dbc1060b4c64d8239883915c0880b/href">https://medium.com/media/990dbc1060b4c64d8239883915c0880b/href</a></iframe><p>You could argue this is abstraction for abstractions sake and that it is pointless. It doesn’t improve readability by all that much after all, yet I think this is way more powerful than the initial scenario, because filter_ingredients can be tested in complete isolation and has no side effects. You can always assume that your return value will be a subset of the ingredients that you passed in. It is said that a human brain has, on average, <a href="https://en.wikipedia.org/wiki/The_Magical_Number_Seven,_Plus_or_Minus_Two">7 threads that it can follow (give or take 2 depending on your physical well-being)</a>. Anytime you can free up a thread by factoring away some code into a pure function is a win for future maintenance and I think not doing it is a wasted opportunity to introduce simplicity. This specific example is really short and could actually be solved by some builtin python functionality, but imagine the filtering process being even slightly more convoluted; being able to forget about 5 or 6 lines of code is worth introducing an additional function, even if it is used only once. Though I generally opt to tackle a problem this way, I am aware of a pretty important tradeoff here: readability. It&#39;s fine when you lift one function out, but it becomes really problematic when you have to scroll up and down in a file (or worse, switch between multiple files) just to understand what is going on. I think there cannot be a general rule in this case, you have to evaluate the implications on readability every single time when making the choice to abstract away some pure computation.</p><h3>Declare Everything</h3><p>Functional Programming is married to the concept of declarative programming. This is in contrast to the imperative style that python promotes. Generally the difference is explained by saying that declarative programming describes <em>what</em> you want and imperative programming describes <em>how</em> you want to get what you want.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ee572353d757b840cb50b372f8716db/href">https://medium.com/media/5ee572353d757b840cb50b372f8716db/href</a></iframe><p>This example is a little unfair, but it is a fantastic demonstration of declarative programming with django and its ORM. I have many things to say about the django ORM, but for now all I will say is that using values and values_list almost exclusively is one of the best decisions you can make. It forces you to understand what data you actually need rather than just grabbing everything, it communicates your intent to any developer that will touch the code after you, and the optimization is just crazy good. This example leverages SQL, but list comprehensions are a good example of a more declarative style of programming. Thanks to list comprehensions you do not need to implement the way that the list is built up, that&#39;s abstracted by the syntactic sugar. This frees up more of those precious threads in your brain.</p><h3>More functions</h3><p>Thinking in functions is the core of FP, much as thinking in objects and object relations is in OOP and I think for me this has become most evident in how I interpret user requirements. Lets say we have 3 tickets on our Jira board:</p><ol><li>As a monkey I want to drink tea</li><li>As a giraffe I want to drink coffee</li><li>As a fish I want to go on long walks on the beach</li></ol><p>If I look at this from an OO perspective, instinctively out comes the crystal ball. The common theme is animals, there is my base class. I see that 2 of the animals want to drink, so I have to have a philosophical debate about whether I am subdividing my animals in amphibians and non-amphibians, or drinkers and non-drinkers, or some other specification. Even if I know that at this point in time there is absolutely no reason to make any abstractions and creating 3 separate classes would probably be fine, the thought of abstraction does cross my mind. And even if I do the smart thing and create 3 classes, the semi-duplicate drinking behavior will bother me.</p><p>Looking at the same requirements from an FP point of view, I know that all I want is functions. I have a function that takes a monkey and tea and produces a zen monkey. I have a function that takes a giraffe and a coffee and produces a hyper giraffe. There is no thinking about hierarchies and classes, just inputs and outputs. This implicitly also makes it easier to solve a more complex problem, if you know the input and output of a complex use case you can start breaking it down at both ends, maybe you need to transform your input to achieve your output, or maybe your output needs to be composed of multiple properties that need to be computed. All of this results in a better idea of what you are going to design.</p><h3>Trivialize order</h3><p>Inherently order matters in an imperative language. The implications of changing the order of your code are pretty good indicator of how well-factored, declarative, and composable your code is. Inheritance and dependency injection are good ways to introduce ordering issues into your code. You can see problems like this arise when you are constructing a Django View with mixins, the order of the mixin is extremely important in the behavior of the view. For a simpler example take the imperative pizza toppings example from earlier, if we moved the topping_names underneath the for loop, this function would not work. There is absolutely no reason to do it in this particular case, but the assignments in this code are volatile in that they have an influence on the code around it. This is fine for a function of 5 lines, but becomes more problematic as your functions get more complex. When you keep in mind that order should matter less, the logical consequence is that your code is more tailored towards composition, because you want to your code to be &#39;mobile&#39;.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de7d287596ca46efdb4d5707afe443bc/href">https://medium.com/media/de7d287596ca46efdb4d5707afe443bc/href</a></iframe><p>In this example the function call order impacts the output. To make it more declarative we compose the functions in a way that declares the intent of what we want to achieve. Not having to remember the order of your program frees up precious brain registers.</p><h3>Even more functions</h3><p>I cannot stress enough how integral functions are to the experience of FP. A great thing about functions is that they have a very limited scope in which they have access to values, unlike classes and objects that have this volatile self property that can be modified by any method in the class. Think of the CreateView and how often the context is overloaded through all of its 9 ancestors, constantly mutating the state of the view. Functional Programming prides itself on having very few side-effects and this is achieved by isolating and minimizing state. Anything that comes into contact with a stateful transaction is tainted with unreliability, so you should contain this to a box and stick warning signs all around it. When I write django code this box comes in 2 forms: state retrieval and state mutation. I keep 2 rules in my head when it comes to state management in django. First, if I need data from a stateful source, I will create an interface function that returns a python type (9 out of 10 times this is a dataclass purely for storing record-like data) that I can then pipe into my pure functions. Custom Querysets are fantastic places to store this type of logic. The other rule is that if I am mutating state, I will do so in a function that has no return value. What this ensures is that I am never dependent on a stateful transaction to have access to my data. I think Manager methods are a pretty good place to store this type of logic. Ultimately it doesn&#39;t really matter how you structure your code, just as long as you are aware that state is a contaminant. It always introduces complexity, so if you can limit the places where its complexity is relevant, then that will greatly improve the maintainability of your code.</p><p>When it comes to state management, invariably you also have to think about data mutability, to which FP says no. Mutating values can give a very false sense of security about your functions. I recently came across something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0cf9e5773b31d666e8f47eec6d0b6ab7/href">https://medium.com/media/0cf9e5773b31d666e8f47eec6d0b6ab7/href</a></iframe><p>A very real danger here is that the variable naming makes it seem as though you have created a new object, when in reality you have only modified an existing object. If you reuse the obj later with the assumption that it has no field property, you will have a bad time. The easy solution is to just not do this. Be mindful of mutability and if at all possible, avoid it. In this case we could rewrite the function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b1c95d4b05ba1c779b0228b0acacf13/href">https://medium.com/media/7b1c95d4b05ba1c779b0228b0acacf13/href</a></iframe><p>With this solution you are no longer mutating the existing object, which is good from an immutability and no side-effects point of view. On the flipside you could argue you have introduced complexity to your function, which has made your application more complex. I would argue however that having mutable data inherently is more complex than any pure function you could write and if you can move complexity away from state into a pure function, you should.</p><h3>Closing thoughts</h3><p>I think that at the center of high-quality code lies simplicity, without it maintainability becomes a nightmare. It’s no wonder the third rule of the <a href="https://www.python.org/dev/peps/pep-0020/">zen of python</a> is that Simple is better than Complex. <a href="https://en.wikipedia.org/wiki/Edsger_W._Dijkstra">Edsger Dijkstra</a> famously said that simplicity is a requirement for reliability. Many smart people seem to agree that simple software is good software. The superpower that functional programmers get from figuring out this unintuitive, mathematically sound way of programming is to make simplicity in code slightly easier. It achieves this by imposing some ideologies about how you approach design and problem solving. It forces you to let go of real-world comparisons to your code and in turn allows you to think clearly about the task at hand without worrying about the future. Its focus on purity in your computation makes it easier to understand how to factor your code into small units. It implores you to write down what you want rather than how to get there which allows you to express your thought process more succinctly. Just being aware of all of these concepts makes you better at designing solutions in your software, which is why it feels so fulfilling to do and why eventually you start preaching FP as if it is some holy deity. If any of this has piqued your interest and you feel like you want to experience all this and finally learn what a monad is, I recommend <a href="http://learnyouahaskell.com/">Learn You a Haskell for Great Good</a>, it is a fantastic (and free) resource about learning haskell. It has amazing examples that introduce FP and showcase its utility and it is the best resource I have found on the internet so far.</p><p>Furthermore, if you are looking for a place where you can learn all of this and more, you might want to check out our <a href="https://careers.labdigital.nl/?lang=en">vacancies</a> page :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96c47d4ca0ba" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lab-digital/functional-programming-in-django-96c47d4ca0ba">Functional Programming in Django</a> was originally published in <a href="https://medium.com/lab-digital">Lab Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sorry, you’re just not my type]]></title>
            <link>https://medium.com/lab-digital/sorry-youre-just-not-my-type-e1b8934c1013?source=rss-418f73904475------2</link>
            <guid isPermaLink="false">https://medium.com/p/e1b8934c1013</guid>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[static-type-checking]]></category>
            <category><![CDATA[mypy]]></category>
            <category><![CDATA[property-based-testing]]></category>
            <dc:creator><![CDATA[Donatas Rasiukevicius]]></dc:creator>
            <pubDate>Wed, 04 Mar 2020 10:42:13 GMT</pubDate>
            <atom:updated>2020-03-04T10:43:35.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9_V_0dDVNmbYR1hdENi6ww.png" /></figure><p>Since the release of python 3.5 (September 2015), it has been possible to add type hints to your code. The full description of the goals and implementation can be read in <a href="https://www.python.org/dev/peps/pep-0484/">PEP484</a>, but it basically boils down to support for static type checking. Static type checking is extremely powerful and in this article I will look at some advanced techniques to get the most out of the typing module, discuss the benefits typing can bring you, and what typing might be able to facilitate in the future. In our organization, we try to incorporate typing in all projects and enforce it with <a href="https://pre-commit.com/">pre-commit hooks</a>. Typing can be introduced gradually and it makes understanding code much easier, especially when multiple developers are working on the same codebase.</p><p>The practice of typing in python consists of adding a type to a variable, like so:</p><pre>a: int = 1</pre><p>This has been introduced with PEP 484 and is inspired by a project called mypy. With mypy and type hints, you as a developer can do static type checking and the reason you would want to do this is so you can catch bugs before shipping your code. The following bug would be caught by the mypy type checker:</p><pre>a: int = &quot;a&quot;</pre><p>Assigning a string value to an int typed var would result in an error. The typing module introduces annotations to deal with more complex types:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0d1b155477bf0f1bbb9eaee30da5436/href">https://medium.com/media/b0d1b155477bf0f1bbb9eaee30da5436/href</a></iframe><p>These are some of the most basic types in the typing module, but the rabbit hole is quite deep. The <a href="https://docs.python.org/3/library/typing.html">documentation</a> is a really good reference on the possibilities, though personally I think it is a little lacking on the topic of generics. My main criticism towards the documentation is that it makes generics look much more complex than they actually are and as a result obfuscates their use-case and the motivation for why you should use them. In my role as software engineer at Lab Digital, I deal with a lot of backend python projects. Introducing typing has helped me with onboarding myself on new projects. In this article I will be sharing some of the cool features and odd quirks that I have found with regard to static type annotations in python. I will <strong>not</strong> be discussing the more basic types as there are plenty of other resources that have done a really good job of explaining the basic usage and the value of using type annotations. Instead, I will look at the stuff that I don’t see in every article (along with some features from python 3.8) and try to shed some light on the use cases.</p><h3>Dataclasses</h3><p><a href="https://docs.python.org/3/library/dataclasses.html">Dataclasses</a> were introduced in python 3.7. Though not necessarily related to typing, I personally find dataclasses work toward the same goal as typing in that they allow you to very concisely define your data structures. I mention them first because I will be using them in the more complex examples later on.</p><p>Where in the past I would have used a dict with a bunch of key/value pairs (because who has the time to write the boilerplate __init__ method), I now almost always opt for a dataclass as they not only tell you more about the available keys, but also about what you can expect from the values. They are also much cleaner than a regular class in python:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/180a8dc26e16b551368025e5386375f6/href">https://medium.com/media/180a8dc26e16b551368025e5386375f6/href</a></iframe><p>Classes (and by extension, dataclasses) are valid types for mypy. So in the following example we would get a mypy error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/080ff9020555b44440515a4359daddbe/href">https://medium.com/media/080ff9020555b44440515a4359daddbe/href</a></iframe><p>I especially like dataclasses when dealing with json-like responses. Where I used to have to consult the API or documentation of the code to figure out what I can expect in the response, I can now just look at the dataclass definition. Personally I think it is good practice to keep dataclasses mostly for storing data, meaning that I try to not add functions to the class and definitely never alter dataclass properties in self methods. It is also important to note that the typing in dataclasses is not restrictive, meaning that the following would run without exceptions:</p><pre>Animal(name=12345)</pre><p>Mypy would catch this error, but python would not bat an eye. Python 3.8 also brings us the TypedDict annotation, which in many ways can fulfil the same use-case as a dataclass. I would recommend using dataclasses unless performance is a really big issue ( dataclasses have slightly more overhead); TypedDict lacks instance and class checks, and has some quirky behaviour during type checking which I will discuss later on alongside the other new features of python 3.8.</p><h3>Type Aliasing and Complex Types</h3><p>The first thing I want to address in regards to typing is type aliasing, specifically how it can be used to simplify data structures and how it can make code more readable. Aliasing is pretty much identical to the variable declaration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62a519329073bb62e69f7dfd33f04a84/href">https://medium.com/media/62a519329073bb62e69f7dfd33f04a84/href</a></iframe><p>Though typing often improves the readability of your code, it can also do the exact opposite. Consider the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87eb3d664ae55b92e6b15072c11bb1b3/href">https://medium.com/media/87eb3d664ae55b92e6b15072c11bb1b3/href</a></iframe><p>If you take the time to analyze this annotation you can figure out roughly what you can expect, but it is far from readable. Type aliasing allows us to simplify this annotation. With type aliasing we can rewrite this annotation to something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/140799a4c11a7c9ff85dc4e0b043789f/href">https://medium.com/media/140799a4c11a7c9ff85dc4e0b043789f/href</a></iframe><p>The annotation is still the same, just broken apart into smaller and more identifiable chunks which makes it much more readable, especially if you are not interested in the entire data structure. But aliasing can take us even further, we can alias primitive types too! This can be tremendously useful in clarifying certain variables that may have obscure names.</p><p>Take the example above, maybe when this function was written the entire application dealt with only 1 type of id and this was fine, but let’s assume the app has grown and more ids are being used throughout. Refactoring may not be a good option because the function is re-used in many places or because insufficient test data exists to find all its implications. Commenting is a relatively good option, but personally I think comments are very easy to miss due to varying styles in commenting code.</p><p>In such a case I would prefer a type alias as you can immediately see what is expected from the function, rather than having to read its documentation. Apart from clarifying variable types, you can also add more context to your data structure. When considering StandardRow and SpecialRow from the example above you could think that the tuples are just inverted, but this doesn&#39;t have to be true:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/808e666a206f715314a71114eaac35a3/href">https://medium.com/media/808e666a206f715314a71114eaac35a3/href</a></iframe><p>Describing your data with meaningful names can add a lot of readability, however it can also introduce unnecessary complexity. Aliasing a primitive type to a custom type requires the person reading this code to know what that primitive type is or to have to locate it somewhere in the project. In this case you might be better suited to renaming StandardRow to something like PersonRow and SpecialRow to AnimalRow and you might achieve the same result in terms of code readability. Finding this balance in when to use type aliasing and when not can be quite hard and mostly depends on style.</p><h3>Generics</h3><p>Simple annotations and type aliasing can go a long way toward clarifying your data structures and your intents, but in some cases you have to deal with some abstract types, think of a function that accepts a Union of types and based upon the input type spits out a specific return value. Consider the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1464c9a43bb428318bc9f03d838f98d5/href">https://medium.com/media/1464c9a43bb428318bc9f03d838f98d5/href</a></iframe><p>When reading this code, we can assume the intention of the function is to rename a Person or an Animal. However, according to mypy the following would be valid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d9f2a33b54a51fac49c725652d8c892/href">https://medium.com/media/8d9f2a33b54a51fac49c725652d8c892/href</a></iframe><p>To clarify this we can introduce generic TypeVars to the code. In terms of readability they might not add a whole lot when compared to Union, but they can be useful in static type checking and other tooling as we will see later on. A TypeVar is a generic type that can have 2 or more constraints (if it has a single constraint you are effectively type aliasing). We can introduce a TypeVar to the code example above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aacc3fd11e3f8ecb1f122891e642d7a5/href">https://medium.com/media/aacc3fd11e3f8ecb1f122891e642d7a5/href</a></iframe><p>This would have the following implications for rename_it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79f225178003071682712d0d7df39841/href">https://medium.com/media/79f225178003071682712d0d7df39841/href</a></iframe><p>The last example is valid according to mypy, however this is where one of the main shortcomings of mypy comes into play: dealing with control flow and generics at the same time. In the case of the last example, the following would also be valid:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5bf06106dafa29e6282a21ad637fa2a8/href">https://medium.com/media/5bf06106dafa29e6282a21ad637fa2a8/href</a></iframe><p>It should be noted that mypy handles simple control flow just fine, the problem only surfaces when dealing with generics as in the example above. The lack of support does not mean that you should not use this pattern, as it still provides a lot of context to your function call.</p><p>TypeVars can be used in conjunction with aliasing for some very concise data type hints:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5aa7c87042726592748a321aad5fd1cc/href">https://medium.com/media/5aa7c87042726592748a321aad5fd1cc/href</a></iframe><h3>Protocols</h3><p>Protocols effectively are what you would call traits or interfaces in other languages and are a derivative of generics. In the context of python you can think of protocols as static duck typing. A very simple example would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76c857d1f5a2ad6e7aa1743c41258666/href">https://medium.com/media/76c857d1f5a2ad6e7aa1743c41258666/href</a></iframe><p>You can even add required variables to your protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e60805a9b39cc770c98e4e4b2521337b/href">https://medium.com/media/e60805a9b39cc770c98e4e4b2521337b/href</a></iframe><p>Protocols can be your best friend when dealing with code that has gone down the path of inheritance and mixins. If you are not the one who wrote it (or you wrote it more than 2 weeks ago), it can be really hard to reason about what is going on:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb6b28750e6feda0ebb07043b758898/href">https://medium.com/media/3bb6b28750e6feda0ebb07043b758898/href</a></iframe><p>Then you end up looking at a function somewhere deep in the project that uses this Obj class and has a bug, and the function may look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/957c7d3d3126ef61149f5b37a8daa499/href">https://medium.com/media/957c7d3d3126ef61149f5b37a8daa499/href</a></iframe><p>In this case it is apparent that the override of fn_b is the problem, but the code might by untyped and then you would have to read through the function and reason about why it is doing what it is doing and in many cases this will also mean figuring out how the functions relate to other functions in the class and all of its parents. In actuality when looking at this function you care about 2 things only:</p><ol><li>The object has 2 specific function definitions</li><li>One of them returns an int</li></ol><p>We can introduce a protocol like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09c608fad0605967d10ba2e6bcdbe073/href">https://medium.com/media/09c608fad0605967d10ba2e6bcdbe073/href</a></iframe><p>And suddenly mypy catches your error; the signature for fn_b is wrong. A very big caveat for this is that this only works for functions with a signature. So if we were remove the return type annotations, mypy would not catch this error.</p><p>An additional feature of protocols is that they can be checked at runtime when you apply the runtime_checkable decorator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f75f949c76fba9d50996e20c2221071/href">https://medium.com/media/9f75f949c76fba9d50996e20c2221071/href</a></iframe><p>Unfortunately, this decorator only works for protocols and cannot be used with something like TypedDict for instance.</p><h3>Hypothesis-auto</h3><p><a href="https://github.com/HypothesisWorks/hypothesis/">Hypothesis</a> is a library that is inspired by <a href="https://hackage.haskell.org/package/QuickCheck">Quickcheck</a> from Haskell. It generates a bunch of test-cases for a function and finds a scenario where the function will yield undesired behavior or raise an error. This is called property-based testing. Introducing hypothesis tests into a codebase can be quite a chore, as you have to learn how hypothesis works, how to generate meaningful call strategies, and how to validate the outcomes. Suddenly quickcheck is not so quick anymore.</p><p>Luckily, <a href="https://pypi.org/user/timothycrosley/">someone</a> created <a href="https://pypi.org/project/hypothesis-auto/">hypothesis-auto</a>. This package takes typed functions as an input and automatically generates test cases by filling random values in for the typed function arguments and validating that the return type matches the annotation and raises no errors. Consider this function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e36b5c7729cb939a08c2a4e077028017/href">https://medium.com/media/e36b5c7729cb939a08c2a4e077028017/href</a></iframe><p>To generate a slew of test cases, we could add hypothesis auto testing:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2463afc8346b57969cc07fbc9885d8e3/href">https://medium.com/media/2463afc8346b57969cc07fbc9885d8e3/href</a></iframe><p>Obviously this is a very simple example, but auto-hypothesis works with complex type hints too:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e18307a0795c5a972ad4f8e2986a482/href">https://medium.com/media/7e18307a0795c5a972ad4f8e2986a482/href</a></iframe><p>This particular case would pass all the generated tests, but let’s imagine that we have discovered a third type of Row in our dataset:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/11d2910cee4dc8469a13ceeb5b741a8b/href">https://medium.com/media/11d2910cee4dc8469a13ceeb5b741a8b/href</a></iframe><p>Just by changing the types, the hypothesis tests will find at least 1 failing condition and you will know that you have to refactor the sum_row function to deal with the scenario of being passed a VerySpecialRow. Below is another example that deals with dataclasses and custom validation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b4dc01b132048d911b19ba32e38e69e/href">https://medium.com/media/8b4dc01b132048d911b19ba32e38e69e/href</a></iframe><p>These tests work for pure functions and may not be very applicable in web-dev. Personally I have a hard time finding the right use-cases for it as so much of web-dev deals with external api-calls, database transactions, and other stateful operations. That said, whenever I am dealing with pure computation/data transformation I always try to incorporate this in my work. Hypothesis auto also cannot infer protocol type annotations, so functions that make use of that cannot be tested adequately with this.</p><h3>Final, Literal, and TypedDict</h3><p>With the latest version of python (3.8 at the time of writing), you have access to Final, Literal, and TypedDict. I mention these separately for two reasons. First, they are only available in python 3.8 and it is unlikely you will be able to incorporate them into an existing project. Second, I have some small concerns about their implementation and the implication this has towards their intended goal.</p><p>A Final annotation indicates that a variable cannot be re-assigned, which sounds interesting from a functional programming point of view.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/957f19aa7b1ca37cd357ff93669be686/href">https://medium.com/media/957f19aa7b1ca37cd357ff93669be686/href</a></iframe><p>Literal is an enum-like annotation that indicates that a variable can only be one of a few values.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f53cfc33a1b0a0595c5b2c6719e1db2/href">https://medium.com/media/7f53cfc33a1b0a0595c5b2c6719e1db2/href</a></iframe><p>TypedDict is a way to annotate a dictionary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6264406ecc8e4904f53be1226f29730/href">https://medium.com/media/a6264406ecc8e4904f53be1226f29730/href</a></iframe><p>Having played around with these for a bit, I have to say I am not all that excited about using them. Final seems incomplete to me. It does not work well with both dataclasses as well as typed dicts:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/085de23555c4d2937816e0f36de32976/href">https://medium.com/media/085de23555c4d2937816e0f36de32976/href</a></iframe><p>You are not really freezing an entire value from my point of view, which undercuts its value tremendously. Literal has some very select use-cases, such as dealing with string arguments for functions like open; specifying a Literal for all the possible read-modes can be pretty powerful. With that said, I cannot remember the last time I used a string argument when dealing with option-like structures; in all cases I would choose an Enum over a Literal. As for TypedDict, I don&#39;t really see the point all that well. The main argument is that it can be useful for legacy codebases where dataclasses are not available, but TypedDict ships with python3.8 and dataclasses come with python3.7. My main criticism is that the type-checking is not intuitive and &#39;lazy&#39; (in terms of type-checking). Consider the following annotation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3f1255b1d76dbfa26ad80fc099a7e1d/href">https://medium.com/media/a3f1255b1d76dbfa26ad80fc099a7e1d/href</a></iframe><p>I would assume that field_c is optional, but instantiating a dict with no field_c raises an error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0e281f2c246ed083c5101a8449735fb/href">https://medium.com/media/d0e281f2c246ed083c5101a8449735fb/href</a></iframe><p>Furthermore, if a field is missing, a TypedDict ignores other type errors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa173cd4a9672ffa97d49133e30c980/href">https://medium.com/media/dfa173cd4a9672ffa97d49133e30c980/href</a></iframe><p>From my point of view, this behaviour makes TypedDict actually less reliable in communicating the intent of the data and for that reason alone I would avoid using it.</p><h3>Closing Remarks and Resources</h3><p>Next to hypothesis-auto, there are more projects that “abuse” the power of typing; <a href="https://github.com/lidatong/dataclasses-json">deserializing json</a> is one that comes to mind and makes a lot of sense. A python compiler in the works ( <a href="https://github.com/python/mypy">mypyc</a>) that aims to compile python code to c modules. Typing can even facilitate <a href="https://tinkering.xyz/abusing-type-annotations/">macros</a>.</p><p>Personally I think type-hints (and dataclasses) facilitate a much cleaner way of writing code and should be embraced by everyone, regardless of the ways in which they will be abused in the future. Being able to reason about the program flow just by looking at data types and not having to figure out what happens to your data with each function call is an immeasurable time-saver. Introducing typing to a project is also a great way of getting yourself familiarized with the various data-flows. Outside of its practical uses for maintaining code, I think forcing yourself to incorporate typing into projects forces you to think differently about data (and data flow), because you have to make all your intentions explicit. Pure functions are a consequence of good typing practices for instance. Things like hypothesis-auto are just a great bonus.</p><p>With typing being optional, it is also very easy to gradually introduce typing into projects. If you want to take it a step further, you could employ pre-commit hooks to check whether all new code is typed. It is important to note that mypy does not catch all errors. Especially when dealing with control flow and generics mypy can fall short and give you a false sense of security. There is no real way to mitigate the danger of this happening, I have looked into using multiple type-checkers at the same time, but this proved to be unreliable because there is no feature-complete type-checker yet. Pyre-check for instance deals better with control flow than mypy, but cannot reason about TypeVar generics as well as mypy and raises incorrect errors. The conclusion here is that you should be aware of the limitations of your type-checker before trusting it blindly. Personally, whenever I am dealing with a tricky/experimental annotation I will make a separate script where I can validate whether an error is actually caught by mypy before integrating the annotation into my code.</p><p>Relevant projects and further reading:</p><ul><li>PEP 484: <a href="https://www.python.org/dev/peps/pep-0484/">https://www.python.org/dev/peps/pep-0484/</a></li><li>mypy: <a href="https://github.com/python/mypy">https://github.com/python/mypy</a></li><li>pyre-check: <a href="https://github.com/facebook/pyre-check">https://github.com/facebook/pyre-check</a></li><li>typing docs: <a href="https://docs.python.org/3.8/library/typing.html">https://docs.python.org/3.8/library/typing.html</a></li><li>hypothesis-auto: <a href="https://github.com/timothycrosley/hypothesis-auto/">https://github.com/timothycrosley/hypothesis-auto/</a></li><li>annotation-abuse (macros in python): <a href="https://tinkering.xyz/abusing-type-annotations/">https://tinkering.xyz/abusing-type-annotations/</a></li><li>dataclasses-json: <a href="https://github.com/lidatong/dataclasses-json">https://github.com/lidatong/dataclasses-json</a></li></ul><p>Thanks for reading my blog!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e1b8934c1013" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lab-digital/sorry-youre-just-not-my-type-e1b8934c1013">Sorry, you’re just not my type</a> was originally published in <a href="https://medium.com/lab-digital">Lab Digital</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>