cachetools-async

0.0.5 · active · verified Thu Apr 16

cachetools-async (version 0.0.5) provides decorators for Python asyncio coroutine functions, enabling memoization by integrating with `cachetools`' cache implementations. It extends the functionality of `cachetools` to the asynchronous world, allowing developers to cache the results of expensive I/O-bound or CPU-bound async operations. The library is in an early development stage (0.0.5) and focuses on offering an asynchronous `@cached` decorator.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the `@cached` decorator with a `TTLCache` for an asynchronous function. The first call to `get_mock_data` for a given `item_id` will execute the function, simulating a delay. Subsequent calls within the `ttl` period for the same `item_id` will return the cached result instantly. After the `ttl` expires, the function will be executed again.

import asyncio
from cachetools import TTLCache
from cachetools_async import cached

# Example of a slow async function (e.g., fetching from an API)
@cached(cache=TTLCache(maxsize=1024, ttl=600)) # Cache for up to 1024 items, with a 600-second (10 minute) TTL
async def get_mock_data(item_id: int):
    print(f"Fetching data for item_id: {item_id}...")
    await asyncio.sleep(2) # Simulate network delay
    return {"id": item_id, "value": f"Data for {item_id}"}

async def main():
    print("First call (should fetch data)")
    data1 = await get_mock_data(1)
    print(f"Result 1: {data1}")

    print("Second call (should use cache)")
    data2 = await get_mock_data(1)
    print(f"Result 2: {data2}")

    print("Third call for a different item (should fetch data)")
    data3 = await get_mock_data(2)
    print(f"Result 3: {data3}")

    # Wait for TTL to expire (for demonstration, normally this would be longer)
    print("Waiting for cache to expire...")
    await asyncio.sleep(601)

    print("Fourth call after TTL (should fetch data again)")
    data4 = await get_mock_data(1)
    print(f"Result 4: {data4}")

if __name__ == "__main__":
    asyncio.run(main())

view raw JSON →