-
-
Notifications
You must be signed in to change notification settings - Fork 61
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
4 changed files
with
58 additions
and
30 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,34 @@ | ||
"""ABC for async classes that need to be cleaned up before exiting.""" | ||
from __future__ import annotations | ||
|
||
import asyncio | ||
import logging | ||
from abc import ABC, abstractmethod | ||
|
||
logging.getLogger(__name__) | ||
|
||
|
||
class Closable(ABC): | ||
"""ABC for async classes that need to be cleaned up before exiting.""" | ||
|
||
def __init__(self, loop: asyncio.AbstractEventLoop | None = None) -> None: | ||
""" | ||
Initialize the ``Closable``. | ||
If an event loop is given, the ``Closable`` will attempt to close itself | ||
using the loop when it is garbage collected. | ||
""" | ||
self._loop: asyncio.AbstractEventLoop | None = loop | ||
|
||
@abstractmethod | ||
async def close(self) -> None: | ||
"""Clean up.""" | ||
raise NotImplementedError | ||
|
||
def __del__(self) -> None: | ||
"""Attempt to automatically clean up when garbage collected.""" | ||
try: | ||
loop = self._loop or asyncio.get_running_loop() | ||
loop.call_soon_threadsafe(loop.create_task, self.close()) | ||
except RuntimeError: | ||
pass |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters