-
Notifications
You must be signed in to change notification settings - Fork 2k
added the solution of task named 'cache-decorator' #2181
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
base: master
Are you sure you want to change the base?
Changes from 2 commits
ef5e806
78a00d6
9d81be4
2e9adde
938a525
c946f21
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,6 +1,24 @@ | ||
| import functools | ||
| from typing import Callable | ||
|
|
||
|
|
||
| def cache(func: Callable) -> Callable: | ||
| # Write your code here | ||
| pass | ||
| cache_dict = {} | ||
| @functools.wraps(func) | ||
|
|
||
| def wrapper(*args, **kwargs) -> Callable: | ||
| if isinstance(kwargs.values(), (list, dict, set)): | ||
| return "Cannot work with mutable data types" | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This manual check for mutable types should be removed. As mentioned in the previous review, returning a string can cause unexpected errors for the function's caller. The standard approach is to let Python raise a Also, this check is not implemented correctly: |
||
|
|
||
| key = (args, tuple(sorted(kwargs.items()))) | ||
|
|
||
| if key in cache_dict: | ||
| print("Getting from cache") | ||
| return cache_dict[key] | ||
|
|
||
| print("Calculating new result") | ||
| result = func(*args, **kwargs) | ||
| cache_dict[key] = result | ||
| return result | ||
|
|
||
| return wrapper | ||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This check for mutable data types has a few issues:
kwargs.values()returns adict_valuesobject, soisinstancewill always beFalse.kwargs) and not positional arguments (args).The task description states this decorator is intended for functions with immutable arguments. Python will automatically raise a
TypeErrorif you try to use an unhashable type (like a list) as part of a dictionary key, which is more informative. It's better to remove this custom check and let Python handle the error.