Skip to content

Commit b5413c4

Browse files
authored
Merge pull request #7 from codeSamuraii/copilot/apply-coding-best-practices-yet-again
Apply coding best practices: strict mypy, remove future annotations, fix async concurrency, hoist imports
2 parents ab5ce87 + a377994 commit b5413c4

8 files changed

Lines changed: 22 additions & 15 deletions

File tree

pyfuse/__main__.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import importlib
1616
import logging
1717
import os
18+
import shutil
1819
import signal
1920
import sys
2021
from collections.abc import Callable
@@ -385,8 +386,6 @@ def _cmd_sandbox(args: argparse.Namespace) -> None:
385386

386387
async def _sandbox_status() -> None:
387388
"""Print the current Docker sandbox status."""
388-
import shutil
389-
390389
if shutil.which("docker") is not None:
391390
from pyfuse.worker.sandbox.docker import (
392391
_container_exists, _container_running, _image_exists,
@@ -410,7 +409,6 @@ async def _sandbox_status() -> None:
410409

411410
async def _docker_setup() -> None:
412411
"""Build the Docker sandbox image."""
413-
import shutil
414412
if shutil.which("docker") is None:
415413
print(
416414
"Error: 'docker' command not found.\n"
@@ -432,7 +430,6 @@ async def _docker_setup() -> None:
432430

433431
async def _docker_teardown() -> None:
434432
"""Stop and remove the Docker sandbox container and image."""
435-
import shutil
436433
if shutil.which("docker") is None:
437434
print("Docker is not installed, nothing to tear down.", file=sys.stderr)
438435
return

pyfuse/graph/tracing.py

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import asyncio
12
import builtins
23
import contextvars
34
import functools
@@ -7,7 +8,7 @@
78
import sys
89
import sysconfig
910
import threading
10-
from collections.abc import AsyncGenerator, Callable, Generator
11+
from collections.abc import AsyncGenerator, Awaitable, Callable, Generator
1112
from pathlib import Path
1213
from typing import Any, ParamSpec, TypeVar, cast
1314

@@ -54,8 +55,15 @@ def _make_map_method(
5455
"""Create the ``.map()`` async method for batch submission and collection."""
5556

5657
async def map(args_list: list[tuple[object, ...]], **kwargs: object) -> list[object]:
57-
results = [await start_method(*args, **kwargs) for args in args_list] # type: ignore[misc]
58-
return [await r for r in results]
58+
coros: list[Awaitable[object]] = [
59+
cast(Awaitable[object], start_method(*args, **kwargs))
60+
for args in args_list
61+
]
62+
results = await asyncio.gather(*coros)
63+
awaitables: list[Awaitable[object]] = [
64+
cast(Awaitable[object], r) for r in results
65+
]
66+
return list(await asyncio.gather(*awaitables))
5967

6068
return map
6169

pyfuse/worker/backends/redis.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from typing import Any
55

66
try:
7-
import redis.asyncio as _redis
7+
import redis.asyncio as _redis # type: ignore[import-not-found]
88
except ImportError:
99
raise ImportError(
1010
"redis package is required for RedisBackend. "

pyfuse/worker/remote.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
import sys
1010
import time
1111
from collections.abc import Awaitable, Callable
12-
from typing import Any
12+
from typing import TYPE_CHECKING, Any
1313

1414
from pyfuse.core.progress import _progress_callback
1515
from pyfuse.core.task import Task
@@ -18,6 +18,9 @@
1818
from pyfuse.worker.result import Result, ResultEnvelope
1919
from pyfuse.worker.worker import Worker
2020

21+
if TYPE_CHECKING:
22+
from pyfuse.worker.sandbox import DockerSandbox
23+
2124
logger = logging.getLogger(__name__)
2225

2326
_active_backend: Backend | None = None
@@ -505,6 +508,7 @@ async def serve(
505508
# Boot the sandbox container before accepting tasks so the first
506509
# execution doesn't pay the startup cost.
507510
if worker.sandboxed:
511+
assert worker._sandbox is not None
508512
await worker._sandbox.start()
509513

510514
logger.info("Listening for tasks \u2014 Ctrl+C to stop.")
@@ -513,6 +517,7 @@ async def serve(
513517
await _worker_loop(worker, backend, concurrency)
514518
finally:
515519
if worker.sandboxed:
520+
assert worker._sandbox is not None
516521
await worker._sandbox.stop()
517522
await disconnect()
518523
logger.info("Worker stopped.")

pyfuse/worker/sandbox/_protocol.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def encode(obj: dict[str, Any]) -> bytes:
2323

2424
def decode_header(data: bytes) -> int:
2525
"""Return the payload length from a 4-byte header."""
26-
(length,) = _HEADER.unpack(data)
26+
length: int = _HEADER.unpack(data)[0]
2727
return length
2828

2929

pyfuse/worker/sandbox/docker.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,6 @@
1616
CI to avoid a cold-start build).
1717
"""
1818

19-
from __future__ import annotations
20-
2119
import asyncio
2220
import logging
2321
import os
@@ -27,6 +25,7 @@
2725
from typing import Any
2826

2927
from pyfuse.core.errors import WorkerError
28+
from pyfuse.core.progress import _progress_callback
3029
from pyfuse.worker.sandbox._protocol import async_recv, async_send
3130

3231
logger = logging.getLogger(__name__)
@@ -113,7 +112,6 @@ async def execute(
113112

114113
# Pick up the host-side progress callback (set by _handle_task)
115114
# so we can forward progress messages from the container.
116-
from pyfuse.core.progress import _progress_callback
117115
progress_cb = _progress_callback.get(None)
118116

119117
try:

pyfuse/worker/sandbox/guest_agent.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@
3838
python guest_agent.py [--host 0.0.0.0] [--port 9749]
3939
"""
4040

41-
from __future__ import annotations
42-
4341
import argparse
4442
import asyncio
4543
import contextvars

pyfuse/worker/worker.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ async def run(self, task: Task) -> Any:
135135
logger.debug("Executing %s (cache key: %s)", task.function_name, cached.subgraph_key)
136136

137137
if self.sandboxed:
138+
assert self._sandbox is not None
138139
# Determine owner_class for method dispatch inside the sandbox
139140
store = Store.from_json(task.graph_json)
140141
target_qname, nodes = store.collect(task.function_name)

0 commit comments

Comments
 (0)