Skip to content

Add proper type hints for synchronous function caching #536

Open
@BenjaminLesieux

Description

@BenjaminLesieux

Description

The current fastapi_cache.decorator.cache() function has type hints that are designed for async functions only, even though the underlying implementation supports both synchronous and asynchronous functions. This causes type checkers to report errors when the decorator is applied to synchronous functions.

Proposed solution

Update the existing decorator's type hints to properly support both synchronous and asynchronous functions.

For now, I managed to avoid the error by wrapping the cache decorator as such:

from fastapi_cache.decorator import cache as fastapi_cache

R = TypeVar("R")
SyncCache = Callable[[Callable[..., R]], Callable[..., R]]


# For synchronous functions
def cache(expire: int) -> SyncCache:
    """
    Creates a synchronous caching decorator
    with the specified expiration time.

    This function wraps `fastapi_cache.decorator.cache()`
    to provide proper type hinting for synchronous functions.
    While the underlying implementation supports
    both sync and async functions,
    the standard FastAPI cache decorator's type
    hints are designed for async functions only.

    Args:
        expire (int): Cache expiration time in seconds.
        Set to 0 for indefinite caching.

    Returns:
        SyncCache: A decorator that can be applied to
        synchronous functions to cache their return values
        based on input parameters.

    See Also:
        fastapi_cache.decorator.cache: The underlying async cache
        implementation.
    """
    return fastapi_cache(expire=expire)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions