From 5223efddb44bbee838cbacb506a5ddb80f4d4d87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Fri, 8 Sep 2023 15:54:11 +0000 Subject: [PATCH] wrapping experiments --- api/asynccontextmanager.py | 45 ++++++++++++++++++++++++++------------ 1 file changed, 31 insertions(+), 14 deletions(-) diff --git a/api/asynccontextmanager.py b/api/asynccontextmanager.py index fba5832..c226773 100644 --- a/api/asynccontextmanager.py +++ b/api/asynccontextmanager.py @@ -4,18 +4,27 @@ from contextlib import asynccontextmanager, contextmanager from io import BytesIO from typing import AsyncContextManager, AsyncIterator, ContextManager, Iterator +from cache import AsyncLRU + +# +# sync impl +# + def get_buf_sync() -> ContextManager[BytesIO]: - @functools.lru_cache - def inner() -> BytesIO: - with open(__file__, "rb") as file: - return BytesIO(file.readline()) + if getattr(get_buf_sync, "inner", None) is None: + + @functools.lru_cache + def inner() -> bytes: + print("sync open") + with open(__file__, "rb") as file: + return file.readline() + + setattr(get_buf_sync, "inner", inner) @contextmanager def ctx() -> Iterator[BytesIO]: - buf = inner() - buf.seek(0) - yield buf + yield BytesIO(get_buf_sync.inner()) return ctx() @@ -26,17 +35,25 @@ def main_sync() -> None: print(buffer.read()) +# +# async impl +# + + async def get_buf_async() -> AsyncContextManager[BytesIO]: - @functools.lru_cache - async def inner() -> BytesIO: - with open(__file__, "rb") as file: - return BytesIO(file.readline()) + if getattr(get_buf_async, "inner", None) is None: + + @AsyncLRU() + async def inner() -> bytes: + print("async open") + with open(__file__, "rb") as file: + return file.readline() + + setattr(get_buf_async, "inner", inner) @asynccontextmanager async def ctx() -> AsyncIterator[BytesIO]: - buf = await inner() - buf.seek(0) - yield buf + yield BytesIO(await get_buf_async.inner()) return ctx()