Rajma Chawal photo by wikipedia user Barthateslisa CC BY_SA 4.0

We can make simple partials using the Python lambda. Here's a Python version of the add function we looked at in Haskell:

def add(x, y):
    return x + y

Python doesn't support currying as part of the language, so we can't just do:


If we try, an exception is raised:

>>> inc = add(1)
Traceback (most recent call last):
File "", line 1, in
TypeError: function takes 2 positional arguments but 1 were given

What we can do is use a lambda as described in this guide:

>>> inc = lambda x: add(1, x)
>>> inc(2)

We can go a bit further with this approach and define a function that does this for us, taking the first argument on which to partially apply add:

def make_adder(x):
    return lambda y: add(x, y)

Now we can use make_adder to, in essence, partially apply add to an argument:

>>> inc = make_adder(1)
>>> inc(2)

Since make_adder is general, we can use it to create any "add a constant" functions. E.g.

>>> add10 = make_adder(10)
>>> add10(5)

This approach can be useful, but requires a specialized partial application function for each case. Python provides the capability to come up with a more general solution.

This guide was first published on Mar 27, 2019. It was last updated on Mar 27, 2019.

This page (Simple Partial Application) was last updated on Mar 23, 2019.

Text editor powered by tinymce.