Given the following function
@lru_cache(maxsize=1)
def get_response_from_api() -> List[ApiObject]:
url = _get_api_url()
response = requests.get(url).text
return json.loads(response, object_hook=_create_api_obj)
when running
mypy predictor --ignore-missing-imports --strict
I am getting the error message:
error: Untyped decorator makes function "get_response_from_api" untyped
How can i fix this ?
How should i annotate the lru_cache function?
Python's functools module comes with the @lru_cache decorator, which gives you the ability to cache the result of your functions using the Least Recently Used (LRU) strategy. This is a simple yet powerful technique that you can use to leverage the power of caching in your code.
lru_cache() documentation for details. Also note that all the decorators in this module are thread-safe by default.
lru_cache basics To memoize a function in Python, we can use a utility supplied in Python's standard library—the functools. lru_cache decorator. Now, every time you run the decorated function, lru_cache will check for a cached result for the inputs provided. If the result is in the cache, lru_cache will return it.
To use LRU caching in Python, you just need to add two lines – import and declaration of the @lru_cache decorator.
This is actually a bug in mypy: https://github.com/python/mypy/issues/5107
According to Ethan Smith (which is a core developer of mypy): as the get_response_from_api
function takes no arguments, the type is inferred as lru_cache[Any]
. This should be fixed
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With