BLOGLLM Logo
Go Pro
Guest
Not signed in
All BlogsCoursesPracticeInterview prepSeriesTagsBookmarksPricing
Log in
All BlogsCoursesPracticeTagsBookmarksPricing
My PrepProblemsStudy PlansResearch PapersRoadmapInterviewContestsLeaderboardGames
Articles
Practice / Agents24 of 28 in topic

777. Write a memoizing decorator that handles lists, dicts and kwargs

MediumAgents Pro

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.

Functiondef 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.

Worked example

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.

Topics
Agents
Similar questions
  • Write the loop that runs a tool-calling agentMedium
  • Retry a flaky tool with exponential backoffMedium
  • Extract a JSON tool call from messy model outputMedium
  • Enforce token and dollar budgets on an agent runMedium
All Agents problems
Report
777 / 903
Python 3solution.pyPython idle
1
2
3
4
def memoize(func):
# return a wrapper with .stats() and .clear()
pass
​
_ex()

This case uses generated data, so it runs as written. Press + to add your own case.

Run checks these cases in your browser, no sign-in needed. Submit checks the full hidden test set with Pro.

Ctrl/Cmd + Enter to run
© BlogLLM, Bengaluru, IndiaAboutTermsPrivacyRefundsDMCAContactRSS