python-diskcache icon indicating copy to clipboard operation
python-diskcache copied to clipboard

Fix a bug to make memorize no longer loss type hint

Open MacHu-GWU opened this issue 2 years ago • 2 comments

#276

I think this is a small fix and should work from 3.5+. If user are on <3.5, the type hint won't work but the code got no impact.

Screen Shot 2023-04-07 at 2 13 43 PM

MacHu-GWU avatar Apr 07 '23 18:04 MacHu-GWU

Can you move this to a type shed or type stubs file? I don’t like maintaining these in the sourcez

grantjenks avatar Apr 08 '23 18:04 grantjenks

I did some research. Looks like this type of decorator + type hint issue cannot be solved by a stub file. The stub file can only define the return type of your @memoize decorator function, but not the inner wrapper of it.

Maybe consider using this decorator <https://pypi.org/project/decorator/>_?

Sorry, I am not the expert on type hint, what I proposed is something that I know would work in 3.5+. I am happy to see that if I could do anything else?

Here's my workaround with the current version 5.4.0, hope this is helpful for other peoples:

# -*- coding: utf-8 -*-

import typing as T
from diskcache import Cache


def decohints(decorator: T.Callable) -> T.Callable:
    return decorator


class TypedCache(Cache):
    def typed_memoize(self, name=None, typed=False, expire=None, tag=None, ignore=()):
        @decohints
        def decorator(func):
            return self.memoize(name, typed, expire, tag, ignore)(func)

        return decorator


cache = TypedCache(...)

MacHu-GWU avatar Apr 09 '23 05:04 MacHu-GWU