[Python] @cached decorator breaks method signature inheritance in subclass

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    I’m using @cached from aiocache on an overridden async method in a subclass. The parent class has a method with a specific return type, and the subclass overrides it with the same return type. But after decorating the subclass method with @cached, I get a type error from pylance:

    "get_all" overrides method of same name in class "IBaseRepository" with incompatible type "_Wrapped[..., Unknown, ..., CoroutineType[Any, Any, Unknown]]"



    Code example:

    from aiocache import cached

    # Base repository
    class IBaseRepository(Generic[T]):
    async def get_all(self) -> List[T]:
    ...

    # Concrete repository
    class CategoryRepositoryImpl(IBaseRepository[CategoryDomain]):
    @cached(ttl=600, key_builder=classaware_key_builder)
    async def get_all(self) -> List[CategoryDomain]:
    return await super().get_all()


    Even if I move caching logic entirely outside the repository method into a use-case or service layer function, applying @cached as a decorator still breaks the function’s signature from the type checker’s perspective.

    If it matters, caching is performed using Redis.

    After adding the @cached decorator, my type checker complains that the method signature is now incompatible. Is there a typing-friendly way to use @cached on subclass methods without breaking method signature inheritance? Or is there a recommended pattern for caching that avoids this problem in type-checked Python code?

    Continue reading...

Compartilhe esta Página