Standard library · 6 / 17 Theory

functools, operator and textwrap

Three more standard library modules that save code and make programs clearer.

functools.lru_cache: automatic memoization

Decorating a function with @lru_cache stores its results: if it is called again with the same arguments, it returns the stored value without running. The arguments must be *hashable*. cache_info() reports the hits (hits) and the real computations (misses).

from functools import lru_cache

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

print(fib(30))                 # 832040
print(fib.cache_info())        # CacheInfo(hits=28, misses=31, maxsize=None, currsize=31)

It is the shortest way to apply the memoization from the complexity lesson. You practice it in Memoization with lru_cache.

functools.partial: fixing arguments

partial creates a new function with some arguments already filled in.

from functools import partial

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

square = partial(power, exponent=2)
cube = partial(power, exponent=3)
print(square(5), cube(2))      # 25 8

operator: functions for the operators

itemgetter and attrgetter build the function passed to key=. With several indexes you sort by several criteria.

from operator import itemgetter, attrgetter

students = [("ann", 9), ("lou", 7), ("eve", 9)]
print(sorted(students, key=itemgetter(1, 0)))
# [('lou', 7), ('ann', 9), ('eve', 9)]

class Book:
    def __init__(self, title, pages):
        self.title = title
        self.pages = pages

books = [Book("B", 300), Book("A", 120)]
print([l.title for l in sorted(books, key=attrgetter("pages"))])   # ['A', 'B']

You apply it in Sorting with itemgetter. The module also offers add, mul, etc., useful with functools.reduce.

textwrap: formatting paragraphs

fill splits a text into lines of a maximum width, shorten trims it adding a marker, and dedent removes the common indentation of a multi-line text.

import textwrap

text = "the sun rises in the east every day"
print(textwrap.fill(text, 12))
# the sun
# rises in the
# east every
# day
print(textwrap.shorten(text, 20, placeholder="..."))   # the sun rises in...
print(textwrap.dedent("""    hello
      world"""))
# hello
#   world

You practice it in Fitting text to a width.