777. Write a memoizing decorator that handles lists, dicts and kwargs
Agents and eval scripts often call the same expensive function (a model call, a tool, a tokenizer) with the same arguments. A decorator can cache the result, but real arguments include lists, dicts and keyword arguments.
Write a decorator memoize(func). The wrapped function returns the cached result when called again with equal arguments. Lists and tuples inside arguments are treated by their contents, dicts by their key-value pairs regardless of order, and keyword argument order does not matter. Positional and keyword arguments are not merged: f(1) and f(x=1) are different keys.
The wrapper must also keep the original __name__ and __doc__, expose wrapper.stats() returning {'hits': h, 'misses': m}, and wrapper.clear() which empties the cache and resets both counters.
def memoize(func)Example 1
Input: decorate f(xs) that
Output: sum(xs); calling f([1, 2]), f([1, 2]), f([3]) then f.stats() returns {'hits': 1, 'misses': 2}
Constraints
- Standard library only.
- Argument values that are not containers are hashable.
Hint 1
Write a recursive freeze helper.
Hint 2
Use functools.wraps on the inner wrapper.
Hint 3
Attach stats and clear as attributes after defining wrapper.
Common mistakes
- Using
str(args)as the key, which breaks when dict order differs. - Forgetting functools.wraps, so the wrapped function loses its name and docstring.
- Resetting stats in clear but not the cache, or the other way round.
Understand the idea
A decorator is a function that takes a function and returns a new one that wraps it. Memoization stores results keyed by the arguments, so a repeated call skips the work. The standard library cache only accepts hashable arguments; real calls pass lists of tokens or dict configs, so you must build a hashable key yourself.
f([1, 2]) twice is one miss then one hit. Tag each container type so [1, 2] and (1, 2) can be told apart if you want, and sort dict items so order does not matter. Agent frameworks use the same trick to deduplicate identical tool calls.