Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

solution py-cache-decorator #1500

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
39 changes: 36 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,39 @@
from typing import Callable
from typing import Callable, Any
from functools import wraps


def cache(func: Callable) -> Callable:
# Write your code here
pass
cache_storage = {}

@wraps(func)
def wrapper(*args) -> Callable:
if not all(isinstance(arg, (int, float, str, tuple, bool))

Choose a reason for hiding this comment

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

The return type hint for wrapper should be Any instead of Callable since it returns the result of the decorated function, which can be of any type.

for arg in args):
raise TypeError("Only immutable argument types")
key = (func.__name__, args)
if key in cache_storage:
print("Getting from cache")
return cache_storage[key]
print("Calculating new result")
cache_storage[key] = func(*args)
return cache_storage[key]
return wrapper


@cache
def long_time_func(base: int, exponent: int, multiplier: int) -> int:
return (base ** exponent ** multiplier) % (base * multiplier)


@cache
def long_time_func_2(n_tuple: tuple, power: int) -> Any:
return [number ** power for number in n_tuple]

Choose a reason for hiding this comment

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

The long_time_func_2 function returns a list, which is mutable. This contradicts the cache's requirement for immutable argument types. Consider returning a tuple instead of a list to ensure immutability.



if __name__ == "__main__":
print(long_time_func(1, 2, 3))
print(long_time_func(2, 2, 3))
print(long_time_func_2((5, 6, 7), 5))
print(long_time_func(1, 2, 3))
print(long_time_func_2((5, 6, 7), 10))
print(long_time_func_2((5, 6, 7), 10))
Loading