Skip to the solution
MediumDSA11 min read

What does the functools module offer?

454 views

The problem

Question presented to candidate: "Tell me about functools. Which parts of it do you actually use, and what problem does each one solve?"

What a strong answer should cover:

  • functools holds higher-order functions: tools that take functions and return functions (or callable objects), for adapting, caching and dispatching.
  • Adapting: partial / partialmethod freeze arguments; wraps (via update_wrapper) copies __name__, __doc__ and sets __wrapped__ on decorator wrappers; reduce folds a sequence; cmp_to_key adapts old compare functions for sorted.
  • Caching: lru_cache(maxsize=...) memoises with LRU eviction and cache_info(); cache (3.9) is the unbounded version; cached_property (3.8) computes once per instance and stores the result in the instance __dict__.
  • Classes and dispatch: total_ordering fills in missing comparison methods from __eq__ plus one of them; singledispatch / singledispatchmethod choose an implementation by the type of the first argument.
  • Trade-offs: cached arguments must be hashable, caches keep references alive (memory leaks on methods), cached_property needs a __dict__, partial is preferable to a lambda because it is introspectable and picklable.

Code / implementation expected: Optional β€” a partial, a wraps-based decorator, or an lru_cache with cache_info().

  • functools

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

11 min read Β· 11 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

Pythonpartial, partialmethod, reduce, wraps, total_ordering and cmp_to_key
Pythonlru_cache, cache, cached_property and singledispatch

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 92 of 139 in Python

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

All Python questions
Up nextMedium

How does Timsort make Python's sort fast and stable?

Continue