Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 14 additions & 2 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,18 @@
from typing import Callable
import functools

g_results = {}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This violates the checklist item: "Use descriptive and correct variable names." The global name g_results (line 4) is not very descriptive. Consider renaming it to something clearer like _cache, cache_store, or results_cache so intent is immediately obvious.



def cache(func: Callable) -> Callable:
# Write your code here
pass
@functools.wraps(func)
def wrapper(*args) -> Callable:
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The wrapper is defined as def wrapper(*args) and therefore does not accept keyword arguments. This will raise a TypeError if a decorated function is called with keywords and also prevents caching calls that differ only by keyword args. The task requires that the decorator stores results for runs with different argument lists (the description states: "number of arguments can also be different"). Consider changing the signature to def wrapper(*args, **kwargs) and include kwargs in the cache key (for example by using a tuple of sorted items or frozenset(kwargs.items())).

result = g_results.get((func.__name__, args))
if result is None:
result = func(*args)
g_results[(func.__name__, args)] = result
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using (func.__name__, args) as the cache key can cause collisions if multiple different functions have the same __name__. This violates the requirement that the decorator "should work correctly with a few decorated functions simultaneously and correctly return results for every function separately." Use the function object itself (e.g. func) or id(func) in the key to reliably distinguish functions. Also, the current logic checks if result is None: which means a legitimately cached value of None will be treated as a cache miss and recomputed. To fix both issues, check cache membership with if key in g_results: or use a sentinel instead of relying on None.

print("Calculating new result")
else:
print("Getting from cache")
return result
return wrapper
Loading