Skip to content

Commit f8335d3

Browse files
committed
Replace asyncio.wait_for with asyncio.timeout
Fallback to using async_timeout on older python asyncio.wait_for has some underlying problems that are only fixed in cpython 3.12. See python/cpython#98518
1 parent 9b039d8 commit f8335d3

File tree

3 files changed

+26
-5
lines changed

3 files changed

+26
-5
lines changed

kasa/protocol.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -14,13 +14,20 @@
1414
import errno
1515
import logging
1616
import struct
17+
import sys
1718
from pprint import pformat as pf
1819
from typing import Dict, Generator, Optional, Union
1920

2021
from .exceptions import SmartDeviceException
2122
from .json import dumps as json_dumps
2223
from .json import loads as json_loads
2324

25+
if sys.version_info[:2] < (3, 11):
26+
from async_timeout import timeout as asyncio_timeout
27+
else:
28+
from asyncio import timeout as asyncio_timeout
29+
30+
2431
_LOGGER = logging.getLogger(__name__)
2532
_NO_RETRY_ERRORS = {errno.EHOSTDOWN, errno.EHOSTUNREACH, errno.ECONNREFUSED}
2633

@@ -79,8 +86,10 @@ async def _connect(self, timeout: int) -> None:
7986
if self.writer:
8087
return
8188
self.reader = self.writer = None
89+
8290
task = asyncio.open_connection(self.host, self.port)
83-
self.reader, self.writer = await asyncio.wait_for(task, timeout=timeout)
91+
async with asyncio_timeout(timeout):
92+
self.reader, self.writer = await task
8493

8594
async def _execute_query(self, request: str) -> Dict:
8695
"""Execute a query on the device and wait for the response."""
@@ -155,9 +164,8 @@ async def _query(self, request: str, retry_count: int, timeout: int) -> Dict:
155164
try:
156165
assert self.reader is not None
157166
assert self.writer is not None
158-
return await asyncio.wait_for(
159-
self._execute_query(request), timeout=timeout
160-
)
167+
async with asyncio_timeout(timeout):
168+
await self._execute_query(request)
161169
except Exception as ex:
162170
await self.close()
163171
if retry >= retry_count:

poetry.lock

Lines changed: 13 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ sphinx_rtd_theme = { version = "^0", optional = true }
3434
sphinxcontrib-programoutput = { version = "^0", optional = true }
3535
myst-parser = { version = "*", optional = true }
3636
docutils = { version = ">=0.17", optional = true }
37+
async-timeout = ">=3.0.0"
3738

3839
[tool.poetry.dev-dependencies]
3940
pytest = "*"

0 commit comments

Comments
 (0)