0Pricing
Python Academy · Lesson

functools: partial and reduce

Create specialized functions with partial and fold sequences with reduce.

functools Overview

functools is a standard-library module of higher-order functions that operate on or return other functions.

import functools

# partial, reduce, lru_cache, wraps, cached_property ...
print(dir(functools))

partial()

functools.partial(func, *args, **kw) creates a new callable with some arguments pre-filled.

import functools

def power(base, exp):
    return base ** exp

square = functools.partial(power, exp=2)
cube   = functools.partial(power, exp=3)

print(square(4))  # 16
print(cube(3))    # 27

All lessons in this course

  1. itertools: Infinite and Finite Iterators
  2. itertools: Combinatorics
  3. functools: partial and reduce
  4. functools: lru_cache and cached_property
← Back to Python Academy