Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type hint: how should type of lru_cache be defined?

Tags:

python

mypy

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?

like image 299
David Michael Gang Avatar asked May 23 '18 19:05

David Michael Gang


People also ask

What does lru_cache do in Python?

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.

Is lru_cache thread safe?

lru_cache() documentation for details. Also note that all the decorators in this module are thread-safe by default.

How do you use the cache function in Python?

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.

How do I import LRU cache?

To use LRU caching in Python, you just need to add two lines – import and declaration of the @lru_cache decorator.


1 Answers

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

like image 98
David Michael Gang Avatar answered Oct 21 '22 03:10

David Michael Gang