Functools module in Python

Functools module in Python

The functools module in Python is part of the standard library and provides higher-order functions and operations on callable objects. Essentially, it offers tools that act on or return other functions.

Here are some of the key functionalities provided by the functools module:

  1. functools.partial(func, *args, **keywords):

    • Returns a new function with partial application of the given arguments and keywords.
    • Useful when you want to "freeze" some portion of a function��s arguments and keywords.
    from functools import partial def multiply(x, y): return x * y # Create a new function that multiplies by 2 double = partial(multiply, 2) print(double(4)) # Outputs: 8 
  2. functools.lru_cache(maxsize=None, typed=False):

    • This is a decorator to wrap a function with a memoizing callable that saves up to the maxsize most recent calls.
    • It can save time in expensive function calls by caching the results.
    from functools import lru_cache @lru_cache(maxsize=None) def fibonacci(n): if n < 2: return n return fibonacci(n-1) + fibonacci(n-2) 
  3. functools.reduce(function, iterable[, initializer]):

    • Applies a function of two arguments cumulatively to the items of an iterable, from left to right.
    • Useful for computing cumulative results.
    from functools import reduce result = reduce(lambda x, y: x*y, [1, 2, 3, 4]) # Outputs: 24 (1*2*3*4) 
  4. functools.wraps(wrapped, assigned=WRAPPER_ASSIGNMENTS, updated=WRAPPER_UPDATES):

    • A decorator for updating the wrapper of a wrapped function, e.g., when you are creating a custom decorator.
    • This helps to maintain the metadata of the original function.
    from functools import wraps def my_decorator(f): @wraps(f) def wrapper(*args, **kwds): print('Calling decorated function') return f(*args, **kwds) return wrapper @my_decorator def example(): """Docstring for example function""" print('Called example function') print(example.__name__) # Outputs: example print(example.__doc__) # Outputs: Docstring for example function 
  5. functools.total_ordering:

    • A class decorator that fills in missing ordering methods.
    • Helps in reducing the boilerplate code for classes that define one or more rich comparison ordering methods.
    from functools import total_ordering @total_ordering class Student: def __init__(self, name): self.name = name def __lt__(self, other): return self.name < other.name def __eq__(self, other): return self.name == other.name 
  6. functools.singledispatch:

    • Transforms a function into a single-dispatch generic function, allowing function overloading based on the type of the first argument.
    • Useful for creating generic functions.

There are other utilities in functools, but the ones highlighted above are some of the most commonly used. It's a powerful module that enhances the capabilities of functions in Python, especially in terms of reusability, memoization, and functional programming patterns.


More Tags

kendo-tabstrip http-live-streaming autocompletetextview data-mining osx-mountain-lion spark-submit operands path android matrix-multiplication

More Programming Guides

Other Guides

More Programming Examples