Python Functools

functools is a module supporting the construction of efficient functions.


Function Composition

The module provides partial and partialmethod functions for function composition.

Try:

from functools import partial

basetwo = partial(int, base=2)
basetwo('10010')               # 18

partialmethod is used in exactly the same way, and just manages the self.

class Cat:
    def say(self, message):
        print(message)

    meow = partialmethod(say, "Meow!")

The module also exposes two objects (functools.Placeholder and functools.partial) which are implementation details of these functions.


Function Overloading

The module provides singledispatch and singledispatchmethod decorators for function overloading.

Try:

from functools import singledispatch

@singledispatch
def makebigger(arg):
    print(arg + 1)

@makebigger.register
def _(arg: string):
    print(arg + "s")

@makebigger.register
def _(list: string):
    print(arg.append(0))

singledispatchmethod is used in exactly the same way, and just dispatches on the second argument (i.e., does not dispatch on the self).


Memoization

The module provides the lru_cache and cache decorators for memoization.

@lru_cache(maxsize=None)
def fib(n):
    if n < 2:
        return n
    return fib(n-1) + fib(n-2)

Note that cache is the same as lru_cache(maxsize=None).

cached_property can be made to work in a similar way.


Others

Function Names

Description

functools.cmp_to_key

functools.reduce

functools.update_wrapper

Decorator Names

Description

functools.total_ordering

functools.wraps


See also

Python functools module documentation

Python Module of the Day article for functools


CategoryRicottone

Python/FuncTools (last edited 2025-12-23 04:34:48 by DominicRicottone)