Monads in Python

Martin McBride
The Startup
Published in
4 min readJun 27, 2020

--

A simple implementation of the Failure monad.

Image by Safijc

Monads have a reputation for being difficult to understand, but in this article we will look at a simple Python implementation of a simple monad. This will hopefully give some insight into what monads are all about.

What is a monad

In functional programming, we use functions as our primary building block, and function composition as one of the basic ways to structure our code. By function composition we mean functions that call other functions, like this:

y = str(neg(int(x)))

This composed function takes a string, converts it to an integer, negates it, and converts it back to a string. So the string “1” is converted to “-1”.

But there is a problem. What if our initial string is something like “XYZ”? Then int will throw a ValueError exception because it can't convert that string to an integer value. We will end up in an exception handler somewhere else in our code, or worse still our program might terminate with an error message. This is exactly the sort unpredictability the functional programming is supposed to solve.

Now imagine if the int function was able to return not only the integer value, but also a flag to say whether the conversion had succeeded or failed…

--

--