wrapping experiments

This commit is contained in:
Jörn-Michael Miehe 2023-09-08 15:54:11 +00:00
parent d27d952d38
commit 5223efddb4

View file

@ -4,18 +4,27 @@ from contextlib import asynccontextmanager, contextmanager
from io import BytesIO from io import BytesIO
from typing import AsyncContextManager, AsyncIterator, ContextManager, Iterator from typing import AsyncContextManager, AsyncIterator, ContextManager, Iterator
from cache import AsyncLRU
#
# sync impl
#
def get_buf_sync() -> ContextManager[BytesIO]: def get_buf_sync() -> ContextManager[BytesIO]:
if getattr(get_buf_sync, "inner", None) is None:
@functools.lru_cache @functools.lru_cache
def inner() -> BytesIO: def inner() -> bytes:
print("sync open")
with open(__file__, "rb") as file: with open(__file__, "rb") as file:
return BytesIO(file.readline()) return file.readline()
setattr(get_buf_sync, "inner", inner)
@contextmanager @contextmanager
def ctx() -> Iterator[BytesIO]: def ctx() -> Iterator[BytesIO]:
buf = inner() yield BytesIO(get_buf_sync.inner())
buf.seek(0)
yield buf
return ctx() return ctx()
@ -26,17 +35,25 @@ def main_sync() -> None:
print(buffer.read()) print(buffer.read())
#
# async impl
#
async def get_buf_async() -> AsyncContextManager[BytesIO]: async def get_buf_async() -> AsyncContextManager[BytesIO]:
@functools.lru_cache if getattr(get_buf_async, "inner", None) is None:
async def inner() -> BytesIO:
@AsyncLRU()
async def inner() -> bytes:
print("async open")
with open(__file__, "rb") as file: with open(__file__, "rb") as file:
return BytesIO(file.readline()) return file.readline()
setattr(get_buf_async, "inner", inner)
@asynccontextmanager @asynccontextmanager
async def ctx() -> AsyncIterator[BytesIO]: async def ctx() -> AsyncIterator[BytesIO]:
buf = await inner() yield BytesIO(await get_buf_async.inner())
buf.seek(0)
yield buf
return ctx() return ctx()