2025-09-12
The functools.cache
function in the Python standard library is amazing, as I’ve previously
noted. But there is one annoying aspect (that I’ve noticed
so far): when you use the @cache decorator, you lose the
type hints on the now-cached function, which your IDE will now interpret
as a lru_cache_wrapper instead of whatever signature it had
before.
So if you have:
from functools import cache
@cache
def my_function(a: int, b: int) -> float:
return a/bAnd you write somewhere else in your code:
c = my_function("abc", 0.5)Your IDE will not give you any warning that you’re doing something wrong. This is a well-known issue, which means that there is also a reasonably easy solution.
We can write our own decorator:
from functools import cache
import inspect
def cache_hint(func):
new_func = cache(func)
new_func.__signature__ = inspect.signature(func)
return new_funcThis simply takes the computed signature of the original function, and bluntly assign it to the new function. It doesn’t sound like it should work, but it does! Now if we do:
@cache_hint
def my_function(a: int, b: int) -> float:
return a/b
c = my_function("abc", 0.5)It will be flagged by the IDE, and you can notice it before you try to divide a string by a float, which is the kind of things an IDE should be able to do.