Skip to content

Commit

Permalink
Add type annotations for method_cache.
Browse files Browse the repository at this point in the history
  • Loading branch information
jaraco committed Dec 20, 2021
1 parent 9fe43da commit 6e75c18
Showing 1 changed file with 17 additions and 5 deletions.
22 changes: 17 additions & 5 deletions jaraco/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@

import more_itertools

from typing import Callable, TypeVar


CallableT = TypeVar("CallableT", bound=Callable[..., object])


def compose(*funcs):
"""
Expand Down Expand Up @@ -92,7 +97,12 @@ def wrapper(*args, **kwargs):
return wrapper


def method_cache(method, cache_wrapper=functools.lru_cache()):
def method_cache(
method: CallableT,
cache_wrapper: Callable[
[CallableT], CallableT
] = functools.lru_cache(), # type: ignore[assignment]
) -> CallableT:
"""
Wrap lru_cache to support storing the cache data in the object instances.
Expand Down Expand Up @@ -160,17 +170,19 @@ def method_cache(method, cache_wrapper=functools.lru_cache()):
for another implementation and additional justification.
"""

def wrapper(self, *args, **kwargs):
def wrapper(self: object, *args: object, **kwargs: object) -> object:
# it's the first call, replace the method with a cached, bound method
bound_method = types.MethodType(method, self)
bound_method: CallableT = types.MethodType( # type: ignore[assignment]
method, self
)
cached_method = cache_wrapper(bound_method)
setattr(self, method.__name__, cached_method)
return cached_method(*args, **kwargs)

# Support cache clear even before cache has been created.
wrapper.cache_clear = lambda: None
wrapper.cache_clear = lambda: None # type: ignore[attr-defined]

return _special_method_cache(method, cache_wrapper) or wrapper
return wrapper # type: ignore[return-value]


def _special_method_cache(method, cache_wrapper):
Expand Down

0 comments on commit 6e75c18

Please sign in to comment.