Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request / Help wanted: Support for coroutines and async functions #22

Open
TheClockTwister opened this issue Apr 26, 2022 · 0 comments

Comments

@TheClockTwister
Copy link

Hi folks,
I really love your module and we even use it at work quit a lot :D
I wanted to contribute and add support for async methods but got stuck since I cannot really access the cache store behind the cached decorator...

here's the basic approach:

import asyncio
from time import perf_counter
from functools import wraps

def log(msg: str):
    print(f"[{round(perf_counter(),3)}]: {msg}")

class AsyncMemoize:
    def __init__(self) -> None:
        self.cache = {} # very silly store for proof of concept

    def __call__(self, function):
        @wraps(function)
        async def wrapped(*args):

            cache_key = hash(args) # 
            if self.cache.get(cache_key, ...) == ...:
                self.cache[cache_key] = await function(*args)
            return self.cache[cache_key]

        return wrapped

@AsyncMemoize()
async def calculate_stuff(n: int):
    await asyncio.sleep(1) # intensive calculation
    return n

async def main():
    log("Calculating...")
    await calculate_stuff(4)
    log("Calculating again...")
    await calculate_stuff(4)
    log("Calculating other...")
    await calculate_stuff(7)
    log("Calculating other again...")
    await calculate_stuff(7)
    log("All done!")

asyncio.run(main())

I could work with the cached decorator, however, this would mean making an async function call sync, and therefore blocking the thread, which is complete bullshit of cause 😆

If you can show me how to access the store directly, I'm gonna fork this repo and implement async support (which is really nice for things like server-side caching on Quart and FastAPI etc.) 😀

Best regards 👋

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant