Zone Of Makos

Menu icon

Function Currying in Python

Function currying is a functional programming technique that involves transforming a function that takes multiple arguments into a series of functions that each take a single argument. In Python, function currying can be achieved using nested functions and closures. Curried functions can be useful for creating reusable and composable code, and they are a common pattern in functional programming.

Nested Functions in Python

Nested functions are functions that are defined inside other functions. In Python, nested functions can access variables from their enclosing scope, even after the enclosing function has returned. This makes them a useful tool for creating closures, which are functions that capture their enclosing state.


def outer_function(x):
    def inner_function(y):
        return x + y
    return inner_function

add_five = outer_function(5)
result = add_five(3)
print(result) # Output: 8

Currying Functions in Python

Currying functions can be achieved using nested functions and closures. The outer function takes the first argument and returns an inner function that takes the second argument, and so on. The final inner function returns the result of the original function.


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

add_five = add(5)
result = add_five(3)
print(result) # Output: 8

Using functools.partial()

The Python standard library includes a module called functools, which provides a function called partial(). partial() allows you to create a new function from an existing function by fixing some of the arguments. This can be useful for currying functions in a more concise and readable way.


from functools import partial

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

add_five = partial(add, 5)
result = add_five(3)
print(result) # Output: 8

Conclusion

Function currying is a useful technique for creating reusable and composable code in Python. It involves transforming a function that takes multiple arguments into a series of functions that each take a single argument. In Python, function currying can be achieved using nested functions and closures, or by using the functools.partial() function from the standard library. By using function currying, you can write more modular and reusable code that is easier to understand and maintain.