70. Function Currying

Here are 10 Python code snippets demonstrating Function Currying, which is the process of pre-filling a function's arguments to create a more specialized version of the function:


1. Basic Function Currying

Currying a function to create specialized versions with some arguments pre-filled.

Copy

def multiply(a, b):
    return a * b

def curry_multiply(a):
    return lambda b: multiply(a, b)

multiply_by_2 = curry_multiply(2)
print(multiply_by_2(5))  # Output: 10

2. Currying with Multiple Arguments

Currying a function that takes multiple arguments.

Copy

def add(a, b, c):
    return a + b + c

def curry_add(a):
    return lambda b, c: add(a, b, c)

add_5 = curry_add(5)
print(add_5(3, 2))  # Output: 10

3. Partial Function Using functools.partial

Using functools.partial to implement currying.

Copy


4. Currying with Default Arguments

Using currying with default values for some arguments.

Copy


5. Currying with Variable Number of Arguments

Currying a function that accepts a variable number of arguments.

Copy


6. Currying for Logging Functions

Using currying to create specialized logging functions.

Copy


7. Currying with Math Operations

Creating specialized functions for common mathematical operations.

Copy


8. Currying for Database Queries

Currying a function that generates database queries.

Copy


9. Currying for Custom Calculations

Creating a curried function for complex calculations.

Copy


10. Currying for String Formatting

Currying a function to format strings.

Copy


These examples demonstrate how currying can simplify function calls by allowing you to pre-fill arguments and create more specialized versions of functions. The technique enhances code readability, especially in cases where certain values are fixed or repeated across multiple calls.

Last updated