Skip to content
This repository has been archived by the owner on Jan 4, 2024. It is now read-only.

Commit

Permalink
Use more accurate type for exception conversion
Browse files Browse the repository at this point in the history
In the wrapper to convert exceptions to a richer exception type,
make use of the new ParamSpec feature to preserve the precise type
of the underlying method.
  • Loading branch information
rra committed Apr 12, 2023
1 parent db14dbc commit 9b6ee12
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions src/rsp_restspawner/spawner.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from __future__ import annotations

import asyncio
from collections.abc import AsyncIterator, Awaitable, Callable
from collections.abc import AsyncIterator, Callable, Coroutine
from dataclasses import dataclass
from datetime import timedelta
from enum import Enum
from functools import wraps
from pathlib import Path
from typing import Any, Optional, TypeVar, cast
from typing import Any, Optional, ParamSpec, TypeVar

from httpx import AsyncClient, HTTPError
from httpx_sse import ServerSentEvent, aconnect_sse
Expand All @@ -23,7 +23,8 @@
SpawnFailedError,
)

F = TypeVar("F", bound=Callable[..., Awaitable[Any]])
P = ParamSpec("P")
T = TypeVar("T")

__all__ = [
"LabStatus",
Expand Down Expand Up @@ -107,17 +108,19 @@ def to_dict(self) -> dict[str, int | str]:
}


def _convert_exception(f: F) -> F:
def _convert_exception(
f: Callable[P, Coroutine[None, None, T]]
) -> Callable[P, Coroutine[None, None, T]]:
"""Convert ``httpx`` exceptions to `ControllerWebError`."""

@wraps(f)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
try:
return await f(*args, **kwargs)
except HTTPError as e:
raise ControllerWebError.from_exception(e) from e

return cast(F, wrapper)
return wrapper


class RSPRestSpawner(Spawner):
Expand Down

0 comments on commit 9b6ee12

Please sign in to comment.