diff --git a/src/art/local/backend.py b/src/art/local/backend.py index 1129326e..1873f1e1 100644 --- a/src/art/local/backend.py +++ b/src/art/local/backend.py @@ -1,3 +1,4 @@ +import asyncio import json import math import os @@ -90,7 +91,26 @@ def __exit__( exc: BaseException | None, tb: TracebackType | None, ) -> None: - self._close() + try: + # If an event loop is running, force users to use the async context manager + asyncio.get_running_loop() + raise RuntimeError( + "LocalBackend used with 'with' inside a running event loop. Use 'async with LocalBackend()' instead." + ) + except RuntimeError: + # No event loop running; safe to close synchronously + self._close() + + async def __aenter__(self) -> Self: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc: BaseException | None, + tb: TracebackType | None, + ) -> None: + await self.close() async def close(self) -> None: """