typestar

functools in Python

partial, reduce and cached_property: three tools worth reaching for.

from functools import cached_property, partial, reduce


def scale(factor, value):
    return factor * value


double = partial(scale, 2)
print(double(21), [double(n) for n in (1, 2, 3)])
print(reduce(lambda a, b: a * b, [1, 2, 3, 4], 1))


class Corpus:
    def __init__(self, words):
        self.words = words

    @cached_property
    def vocabulary(self):
        print("computing once")
        return sorted(set(self.words))


corpus = Corpus(["a", "b", "a"])
print(corpus.vocabulary, corpus.vocabulary)

How it works

  1. partial freezes arguments and returns a callable.
  2. cached_property computes once per instance, then stores.
  3. reduce folds a sequence when there is no built-in for it.

Keywords and builtins used here

The run, in numbers

Lines
24
Characters to type
470
Tokens
145
Three-star pace
105 tpm

At the three-star pace of 105 tokens a minute, this run takes about 83 seconds.

Type this snippet

Step 1 of 3 in functools & operator, step 38 of 53 in Pythonic Python.

← Previous Next →