Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: proper error handling on __exit__ and __aexit__ of Container #113

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 17 additions & 7 deletions src/svcs/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -541,7 +541,7 @@ def __exit__(
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
self.close()
self.close(exc_type, exc_val, exc_tb)

async def __aenter__(self) -> Container:
return self
Expand All @@ -552,7 +552,7 @@ async def __aexit__(
exc_val: BaseException | None,
exc_tb: TracebackType | None,
) -> None:
await self.aclose()
await self.aclose(exc_type, exc_val, exc_tb)

def __del__(self) -> None:
"""
Expand All @@ -565,7 +565,12 @@ def __del__(self) -> None:
stacklevel=1,
)

def close(self) -> None:
def close(
self,
exc_type: type[BaseException] | None = None,
exc_val: BaseException | None = None,
exc_tb: TracebackType | None = None,
) -> None:
"""
Run all registered *synchronous* cleanups.

Expand All @@ -589,7 +594,7 @@ def close(self) -> None:
)
continue

cm.__exit__(None, None, None)
cm.__exit__(exc_type, exc_val, exc_tb)
except Exception: # noqa: BLE001
log.warning(
"Container clean up failed for %r.",
Expand All @@ -603,7 +608,12 @@ def close(self) -> None:
self._on_close.clear()
self._instantiated.clear()

async def aclose(self) -> None:
async def aclose(
self,
exc_type: type[BaseException] | None = None,
exc_val: BaseException | None = None,
exc_tb: TracebackType | None = None,
) -> None:
"""
Run *all* registered cleanups -- synchronous **and** asynchronous.

Expand All @@ -619,9 +629,9 @@ async def aclose(self) -> None:
for name, cm in reversed(self._on_close):
try:
if isinstance(cm, AbstractContextManager):
cm.__exit__(None, None, None)
cm.__exit__(exc_type, exc_val, exc_tb)
else:
await cm.__aexit__(None, None, None)
await cm.__aexit__(exc_type, exc_val, exc_tb)

except Exception: # noqa: BLE001, PERF203
log.warning(
Expand Down