Can I apply functools.wraps to a normal function, which is not a decorator or a decorator factory?

46 Views Asked by At

I have a function like this

def load_resources(path: Path, src_type: str, *, load_all: bool = False) -> bool:
    ... # something happens here and return a value

Then IDE(which is VScode in this case) gives me useful information when using load_resources including this kind of type hint.

(function) def load_resources(path: Path, src_type: str, *, load_all: bool = False) -> bool

Calling the function takes some time so I wanted to put functools.lru_cache on the function. (I am using python3.8)

@functools.lru_cache()
def load_resources(path: Path, src_type: str, *, load_all: bool = False) -> bool:
    ...

Then lru_cache shades the information of load_resources.

(function) load_resources: _lru_cache_wrapper[Unknown]

So I tried functools.wraps like this.

def __load_resources(path: Path, src_type: str, *, load_all: bool = False) -> bool:
    ...

@functools.wraps(__load_resources)
@functools.lru_cache()
def load_resources(*args, **kwargs):
    return __load_resources(*args, **kwargs)

but it gives me a weird type hint like this.

(function) load_resources: _Wrapped[(__load_resources(path: Path, src_type: str, *, load_all: bool = False), bool, (*args: Hashable, **kwargs: Hashable), Unknown]

I knew that __name__ of the function went wrong but I thought other features will be applied properly.

Is it just wrong using functools.wraps out of the context of decorators? Then how can I attach type hints to the functions decorated by functools.lru_cache?


I just did like this.

def load_resources(path: Path, src_type: str, *, load_all: bool = False) -> bool:
    return __get_context(path, src_type, load_all=load_all)
0

There are 0 best solutions below