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 typing import AsyncContextManager, AsyncIterator, ContextManager, Iterator
from cache import AsyncLRU
#
# sync impl
#
def get_buf_sync() -> ContextManager[BytesIO]:
if getattr(get_buf_sync, "inner", None) is None:
@functools.lru_cache
def inner() -> BytesIO:
def inner() -> bytes:
print("sync open")
with open(__file__, "rb") as file:
return BytesIO(file.readline())
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:
if getattr(get_buf_async, "inner", None) is None:
@AsyncLRU()
async def inner() -> bytes:
print("async open")
with open(__file__, "rb") as file:
return BytesIO(file.readline())
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()