Skip to content

Commit 3587df8

Browse files
committed
Fix typing for py3.8
1 parent 4f79242 commit 3587df8

File tree

8 files changed

+221
-47
lines changed

8 files changed

+221
-47
lines changed

Diff for: .python_version

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.8

Diff for: choreographer/_brokers/_async.py

+12-4
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import asyncio
44
import warnings
5+
from functools import partial
56
from typing import TYPE_CHECKING
67

78
import logistro
@@ -127,9 +128,11 @@ def check_read_loop_error(result: asyncio.Future[Any]) -> None:
127128
raise e
128129

129130
async def read_loop() -> None: # noqa: PLR0912, PLR0915, C901
130-
responses = await asyncio.to_thread(
131-
self._channel.read_jsons,
132-
blocking=True,
131+
loop = asyncio.get_running_loop()
132+
fn = partial(self._channel.read_jsons, blocking=True)
133+
responses = await loop.run_in_executor(
134+
executor=None,
135+
func=fn,
133136
)
134137
_logger.debug(f"Channel read found {len(responses)} json objects.")
135138
for response in responses:
@@ -244,7 +247,12 @@ async def write_json(
244247
_logger.debug(f"Created future: {key} {future}")
245248
try:
246249
async with self._write_lock:
247-
await asyncio.to_thread(self._channel.write_json, obj)
250+
loop = asyncio.get_running_loop()
251+
await loop.run_in_executor(
252+
None,
253+
self._channel.write_json,
254+
obj,
255+
)
248256
except BaseException as e: # noqa: BLE001
249257
future.set_exception(e)
250258
del self.futures[key]

Diff for: choreographer/browser_async.py

+11-7
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,8 @@ def run() -> subprocess.Popen[bytes]:
131131
)
132132

133133
_logger.debug("Trying to open browser.")
134-
self.subprocess = await asyncio.to_thread(run)
134+
loop = asyncio.get_running_loop()
135+
self.subprocess = await loop.run_in_executor(None, run)
135136

136137
super().__init__("0", self._broker)
137138
self._add_session(Session("", self._broker))
@@ -166,7 +167,8 @@ async def _is_closed(self, wait: int | None = 0) -> bool:
166167
return not _is_open
167168
else:
168169
try:
169-
await asyncio.to_thread(self.subprocess.wait, wait)
170+
loop = asyncio.get_running_loop()
171+
await loop.run_in_executor(None, self.subprocess.wait, wait)
170172
except subprocess.TimeoutExpired:
171173
return False
172174
return True
@@ -184,8 +186,8 @@ async def _close(self) -> None:
184186
return
185187
except ChannelClosedError:
186188
_logger.debug("Can't send Browser.close on close channel")
187-
188-
await asyncio.to_thread(self._channel.close)
189+
loop = asyncio.get_running_loop()
190+
await loop.run_in_executor(None, self._channel.close)
189191

190192
if await self._is_closed(wait=3):
191193
return
@@ -194,7 +196,8 @@ async def _close(self) -> None:
194196
_logger.debug("Browser is closed after closing channel")
195197
return
196198
_logger.warning("Resorting to unclean kill browser.")
197-
await asyncio.to_thread(kill, self.subprocess)
199+
loop = asyncio.get_running_loop()
200+
await loop.run_in_executor(None, kill, self.subprocess)
198201
if await self._is_closed(wait=4):
199202
return
200203
else:
@@ -237,12 +240,13 @@ async def _watchdog(self) -> None:
237240
with warnings.catch_warnings():
238241
warnings.filterwarnings("ignore", category=TmpDirWarning)
239242
_logger.debug("Starting watchdog")
240-
await asyncio.to_thread(self.subprocess.wait)
243+
loop = asyncio.get_running_loop()
244+
await loop.run_in_executor(None, self.subprocess.wait)
241245
_logger.warning("Browser is being closed by watchdog.")
242246
self._watch_dog_task = None
243247
await self.close()
244248
await asyncio.sleep(1)
245-
await asyncio.to_thread(self._browser_impl.clean)
249+
await loop.run_in_executor(None, self._browser_impl.clean)
246250

247251
def _add_tab(self, tab: Tab) -> None:
248252
if not isinstance(tab, Tab):

Diff for: choreographer/channels/pipe.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ def write_json(self, obj: Mapping[str, Any]) -> None:
7171
raise ChannelClosedError
7272
encoded_message = wire.serialize(obj) + b"\0"
7373
_logger.debug(
74-
f"Writing message {encoded_message[:15]}...{encoded_message[-15:]}, "
74+
f"Writing message {encoded_message[:15]!r}...{encoded_message[-15:]!r}, "
7575
f"size: {len(encoded_message)}.",
7676
)
7777
_logger.debug2(f"Full Message: {encoded_message!r}")
@@ -125,13 +125,13 @@ def read_jsons( # noqa: PLR0912, PLR0915, C901 branches, complexity
125125
10000,
126126
) # 10MB buffer, nbd, doesn't matter w/ this
127127
_logger.debug(
128-
f"First read in loop: {raw_buffer[:15]}...{raw_buffer[-15:]}. "
128+
f"First read in loop: {raw_buffer[:15]!r}...{raw_buffer[-15:]!r}. "
129129
f"size: {len(raw_buffer)}.",
130130
)
131131
_logger.debug2(f"Whole buffer: {raw_buffer!r}")
132132
if not raw_buffer or raw_buffer == b"{bye}\n":
133133
if raw_buffer:
134-
_logger.debug(f"Received {raw_buffer}. is bye?")
134+
_logger.debug(f"Received {raw_buffer!r}. is bye?")
135135
# we seem to need {bye} even if chrome closes NOTE
136136
self.close()
137137
raise ChannelClosedError
@@ -152,7 +152,8 @@ def read_jsons( # noqa: PLR0912, PLR0915, C901 branches, complexity
152152
# this could be hard to test as it is a real OS corner case
153153
finally:
154154
_logger.debug(
155-
f"Total loops: {loop_count}, " f"Final size: {len(raw_buffer)}.",
155+
f"Total loops: {loop_count}, "
156+
f"Final size: {len(raw_buffer) if raw_buffer else 0}.",
156157
)
157158
_logger.debug2(f"Whole buffer: {raw_buffer!r}")
158159
decoded_buffer = raw_buffer.decode("utf-8")

Diff for: choreographer/cli/_cli_utils.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import urllib.request
1010
import warnings
1111
import zipfile
12+
from functools import partial
1213
from pathlib import Path
1314

1415
# SOON TODO this isn't the right download path, look at uv, use sysconfig
@@ -134,12 +135,11 @@ async def get_chrome(
134135
verbose: print out version found
135136
136137
"""
137-
return await asyncio.to_thread(
138-
get_chrome_sync,
139-
arch=arch,
140-
i=i,
141-
path=path,
142-
verbose=verbose,
138+
loop = asyncio.get_running_loop()
139+
fn = partial(get_chrome_sync, arch=arch, i=i, path=path, verbose=verbose)
140+
return await loop.run_in_executor(
141+
executor=None,
142+
func=fn,
143143
)
144144

145145

Diff for: choreographer/protocol/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,14 @@
88

99
from collections.abc import MutableMapping
1010
from enum import Enum
11-
from typing import Any, NewType, Optional, cast
11+
from typing import Any, NewType, Optional, Tuple, cast
1212

1313
BrowserResponse = NewType("BrowserResponse", MutableMapping[str, Any])
1414
"""The type for a response from the browser. Is really a `dict()`."""
1515
BrowserCommand = NewType("BrowserCommand", MutableMapping[str, Any])
1616
"""The type for a command to the browser. Is really a `dict()`."""
1717

18-
MessageKey = NewType("MessageKey", tuple[str, Optional[int]])
18+
MessageKey = NewType("MessageKey", Tuple[str, Optional[int]])
1919
"""The type for id'ing a message/response. It is `tuple(session_id, message_id)`."""
2020

2121

Diff for: pyproject.toml

+5-5
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ enabled = true
1212
name = "choreographer"
1313
description = "Devtools Protocol implementation for chrome."
1414
readme = "README.md"
15-
requires-python = ">=3.9"
15+
requires-python = ">=3.8"
1616
dynamic = ["version"]
1717
authors = [
1818
{name = "Andrew Pikul", email="[email protected]"},
@@ -22,7 +22,7 @@ maintainers = [
2222
{name = "Andrew Pikul", email = "[email protected]"},
2323
]
2424
dependencies = [
25-
"logistro>=1.0.9",
25+
"logistro>=1.0.11",
2626
"simplejson",
2727
]
2828

@@ -40,10 +40,10 @@ dev = [
4040
"pytest-asyncio",
4141
"pytest-xdist",
4242
"async-timeout",
43-
"poethepoet>=0.31.1",
4443
"numpy",
4544
"mypy>=1.14.1",
4645
"types-simplejson>=3.19.0.20241221",
46+
"poethepoet>=0.30.0",
4747
]
4848

4949
# uv doens't allow dependency groups to have separate python requirements
@@ -58,8 +58,8 @@ dev = [
5858
#]
5959

6060
[tool.uv.sources]
61-
mkquixote = { path = "../mkquixote", editable = true }
62-
logistro = { path = "../logistro", editable = true }
61+
#mkquixote = { path = "../mkquixote", editable = true }
62+
#logistro = { path = "../logistro", editable = true }
6363

6464
[tool.ruff.lint]
6565
select = ["ALL"]

0 commit comments

Comments
 (0)