Skip to content
Open
Changes from 2 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
22 changes: 20 additions & 2 deletions app/main.py
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"
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 check for mutable data types has a few issues:

  1. It doesn't work as intended because kwargs.values() returns a dict_values object, so isinstance will always be False.
  2. It only checks keyword arguments (kwargs) and not positional arguments (args).
  3. Returning a string can cause type errors for the code that calls the decorated function.

The task description states this decorator is intended for functions with immutable arguments. Python will automatically raise a TypeError if 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.

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 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 TypeError if an unhashable (mutable) argument is used, which will happen automatically when creating the key on line 13.

Also, this check is not implemented correctly: isinstance on kwargs.values() will not work as you expect, and it completely ignores mutable types passed in *args.


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
Loading