Skip to content
Open
Changes from all commits
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
20 changes: 17 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
from typing import Callable
import functools


_function_caches = {}
def cache(func: Callable) -> Callable:
# Write your code here
pass
if func not in _function_caches:
_function_caches[func] = {}
Comment on lines +4 to +7

Choose a reason for hiding this comment

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

While using a global dictionary works for this task, it's generally better to avoid global state. A more robust and self-contained approach is to create the cache inside the decorator function, allowing each decorated function to have its own cache captured in a closure. This prevents potential issues in larger applications where global variables can be modified unexpectedly.

Consider this alternative structure:

def cache(func: Callable) -> Callable:
    local_cache = {}  # This cache is private to each decorated function

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        # ... your caching logic here using 'local_cache' ...

    return wrapper

@functools.wraps(func)
def wrapper(*args, **kwargs):
sorted_kwargs = tuple(sorted(kwargs.items()))
cache_key = (args, sorted_kwargs)
if cache_key in _function_caches[func]:
print("Getting from cache")
return _function_caches[func][cache_key]
else:
print("Calculating new result")
result = func(*args, **kwargs)
_function_caches[func][cache_key] = result
return result
return wrapper
Loading