Skip to content

Commit

Permalink
fix: Run closable cleanup on exit
Browse files Browse the repository at this point in the history
  • Loading branch information
malmeloo committed Aug 2, 2024
1 parent 5cfb328 commit 7a69f73
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 9 deletions.
2 changes: 1 addition & 1 deletion examples/fetch_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from findmy.reports import RemoteAnisetteProvider

# URL to (public or local) anisette server
ANISETTE_SERVER = "https://ani.intra.mikealmel.ooo"
ANISETTE_SERVER = "http://localhost:6969"

logging.basicConfig(level=logging.INFO)

Expand Down
25 changes: 17 additions & 8 deletions findmy/util/closable.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
"""ABC for async classes that need to be cleaned up before exiting."""

from __future__ import annotations

import asyncio
import atexit
import contextlib
import logging
from abc import ABC, abstractmethod

Expand All @@ -20,18 +23,24 @@ def __init__(self, loop: asyncio.AbstractEventLoop | None = None) -> None:
"""
self._loop: asyncio.AbstractEventLoop | None = loop

atexit.register(self.close_sync)

@abstractmethod
async def close(self) -> None:
"""Clean up."""
raise NotImplementedError

def close_sync(self) -> None:
"""Clean up."""
atexit.unregister(self.close_sync)

loop = self._loop or asyncio.get_event_loop()
if loop.is_running():
loop.call_soon_threadsafe(loop.create_task, self.close())
else:
loop.run_until_complete(self.close())

def __del__(self) -> None:
"""Attempt to automatically clean up when garbage collected."""
try:
loop = self._loop or asyncio.get_running_loop()
if loop.is_running():
loop.call_soon_threadsafe(loop.create_task, self.close())
else:
loop.run_until_complete(self.close())
except RuntimeError:
pass
with contextlib.suppress(RuntimeError):
self.close_sync()

0 comments on commit 7a69f73

Please sign in to comment.