← Back to Python

All Topics

Advertisement

Learn/Python/Python Advanced

Function Composition

Topic: Functional Programming

Advertisement

Introduction

Function composition is the process of combining simple functions to build more complex operations. Python can implement composition using pipes and composition tools.

Basic Composition

def compose(*functions):
    def composed(x):
        for f in reversed(functions):
            x = f(x)
        return x
    return composed

def add_one(x):
    return x + 1

def double(x):
    return x * 2

def square(x):
    return x ** 2

pipeline = compose(square, double, add_one)
print(pipeline(5))  # (5 + 1) * 2 = 12, then 12 ** 2 = 144

Pipe Function

def pipe(value, *functions):
    for f in functions:
        value = f(value)
    return value

result = pipe(5, add_one, double, square)
print(result)  # 144

Compose with Multiple Arguments

from functools import reduce

def compose(*functions):
    return lambda *args: reduce(
        lambda x, f: f(*x) if isinstance(x, tuple) else f(x),
        functions,
        args
    )

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

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

def apply_all(*args):
    return lambda f: f(*args)

composed = compose(multiply, add)
print(composed(2, 3))  # add(2,3) = 5, multiply(5) = error

Functional Tools

from functools import reduce

class Functional:
    @staticmethod
    def compose(*funcs):
        return lambda x: reduce(lambda v, f: f(v), funcs, x)
    
    @staticmethod
    def pipe(*funcs):
        return Functional.compose(*reversed(funcs))
    
    @staticmethod
    def curry(func):
        def curried(*args):
            if len(args) >= func.__code__.co_argcount:
                return func(*args)
            return lambda *more: curried(*(args + more))
        return curried

add = Functional.curry(lambda a, b: a + b)
add(1)(2)  # 3

Composable Class

class Composable:
    def __init__(self, func):
        self.func = func
    
    def __call__(self, *args, **kwargs):
        return self.func(*args, **kwargs)
    
    def __or__(self, other):
        return Composable(lambda x: other(self(x)))
    
    def __ror__(self, other):
        return Composable(lambda x: self(other(x)))

@Composable
def double(x):
    return x * 2

@Composable
def add_one(x):
    return x + 1

result = (double | add_one)(5)  # 11

Practice Problems

  1. Compose multiple string functions
  2. Create pipe utility for data processing
  3. Implement compose with keyword args
  4. Build composable decorator
  5. Use composition in data pipeline

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →