Émerson Silva

Software Engineer @oivitalk

Home

Currying with Python [EN]

Published Nov 02, 2018

Currying: WHAT IS and HOW WORKS

Currying is a functional technique, that allow us to use a function partially, that means, we can pass an arbitrary number of arguments smaller than the original, and will return another function that receives the remaining ones, ‘till the number of them reaches the original.

The way that I implemented Currying allow to use decorator(@) notation (an elegant way to wrap a function or even a class into another function):

from Curry import curry

@curry
def split_by(character, word):
    return word.split(character)

OR passing the function to be curried to curry function.

def split_by(character, word):
    return word.split(character)

split_by = curry(split_by)

Demostration:

split_by_spaces = split_by(' ')
split_by_spaces('Hello my name is Emerson')
#['Hello', 'my', 'name', 'is', 'Emerson']

Implementing

First of all we need to know the paramaters number of a function, to do that I used signature() method from inspect bult-in module.

# Curry.py

from inspect import signature


def get_params_len(fn): return len(signature(fn).parameters)

And now we have to temporarily save the arguments passed to some wrapper function that will be returned, until the amount of arguments reach the original length.

# Curry.py

def curry(fn):
    # get parameters length of the original function
    fn_params_len = get_params_len(fn)
    # save temporarily the paramaters
    temp_params = []

    def _(*args):
        if (len(args) + len(temp_params)) <= fn_params_len:
            [temp_params.append(arg) for arg in args]
    
            if len(temp_params) == fn_params_len:
                __ = temp_params.copy()
                temp_params.clear()
		        return fn(*__)
            
            return _

        raise Exception('Number of arguments was too much')

    return _

Ps: Code tested in Python 3.5