From c865d3f02c34fbbcd310f97087699e819a30b892 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 30 Jan 2022 16:00:00 -0600 Subject: [PATCH] Fix unsafe __del__ in TPLinkSmartHomeProtocol (#300) * Fix unsafe __del__ in TPLinkSmartHomeProtocol Fixes ``` Exception ignored in: Traceback (most recent call last): File "/Users/bdraco/home-assistant/venv/lib/python3.9/site-packages/kasa/protocol.py", line 159, in __del__ self.writer.close() File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/streams.py", line 353, in close return self._transport.close() File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/selector_events.py", line 700, in close self._loop.call_soon(self._call_connection_lost, None) File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 748, in call_soon self._check_thread() File "/opt/homebrew/Cellar/python@3.9/3.9.6/Frameworks/Python.framework/Versions/3.9/lib/python3.9/asyncio/base_events.py", line 785, in _check_thread raise RuntimeError( RuntimeError: Non-thread-safe operation invoked on an event loop other than the current one ``` * comment * comment * comment --- kasa/protocol.py | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/kasa/protocol.py b/kasa/protocol.py index 14de9c6c..e2f94626 100755 --- a/kasa/protocol.py +++ b/kasa/protocol.py @@ -156,7 +156,11 @@ class TPLinkSmartHomeProtocol: def __del__(self) -> None: if self.writer and self.loop and self.loop.is_running(): - self.writer.close() + # Since __del__ will be called when python does + # garbage collection is can happen in the event loop thread + # or in another thread so we need to make sure the call to + # close is called safely with call_soon_threadsafe + self.loop.call_soon_threadsafe(self.writer.close) self._reset() @staticmethod