-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
18 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,22 @@ | ||
from typing import Callable | ||
import functools | ||
|
||
|
||
def cache(func: Callable) -> Callable: | ||
# Write your code here | ||
pass | ||
cache_storage = {} | ||
|
||
@functools.wraps(func) | ||
def wrapper(*args: any, **kwargs: any) -> any: | ||
# Sort the keyword arguments | ||
kwargs_tuple = tuple(sorted(kwargs.items())) | ||
key = (args, kwargs_tuple) | ||
# Check if this key exists in the cache | ||
if key in cache_storage: | ||
print("Getting from cache") | ||
return cache_storage[key] | ||
# Calculate and store the result | ||
print("Calculating new result") | ||
result = func(*args, **kwargs) | ||
cache_storage[key] = result | ||
return result | ||
return wrapper |