From e894aad746fd3472eeec14f80ba95297d8303d80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?J=C3=B6rn-Michael=20Miehe?= Date: Fri, 8 Sep 2023 16:08:10 +0000 Subject: [PATCH] experimental success --- api/asynccontextmanager.py | 59 +++++++++++++++----------------------- 1 file changed, 23 insertions(+), 36 deletions(-) diff --git a/api/asynccontextmanager.py b/api/asynccontextmanager.py index c226773..25abf5c 100644 --- a/api/asynccontextmanager.py +++ b/api/asynccontextmanager.py @@ -1,38 +1,32 @@ import asyncio import functools -from contextlib import asynccontextmanager, contextmanager from io import BytesIO -from typing import AsyncContextManager, AsyncIterator, ContextManager, Iterator from cache import AsyncLRU +FILES = __file__, "pyproject.toml" +REPS = 3 + # # sync impl # -def get_buf_sync() -> ContextManager[BytesIO]: - if getattr(get_buf_sync, "inner", None) is None: +@functools.lru_cache +def get_bytes_sync(fn) -> bytes: + print("sync open") + with open(fn, "rb") as file: + return file.readline() - @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]: - yield BytesIO(get_buf_sync.inner()) - - return ctx() +def get_buf_sync(fn) -> BytesIO: + return BytesIO(get_bytes_sync(fn)) def main_sync() -> None: - for _ in range(2): - with get_buf_sync() as buffer: - print(buffer.read()) + for fn in FILES: + for _ in range(REPS): + print(get_buf_sync(fn).read()) # @@ -40,28 +34,21 @@ def main_sync() -> None: # -async def get_buf_async() -> AsyncContextManager[BytesIO]: - if getattr(get_buf_async, "inner", None) is None: +@AsyncLRU() +async def get_bytes_async(fn) -> bytes: + print("async open") + with open(fn, "rb") as file: + return file.readline() - @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]: - yield BytesIO(await get_buf_async.inner()) - - return ctx() +async def get_buf_async(fn) -> BytesIO: + return BytesIO(await get_bytes_async(fn)) async def main_async() -> None: - for _ in range(2): - async with await get_buf_async() as buffer: - print(buffer.read()) + for fn in FILES: + for _ in range(REPS): + print((await get_buf_async(fn)).read()) if __name__ == "__main__":