Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhance typing for cloud_api decorators #559

Merged
merged 1 commit into from
Feb 5, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 20 additions & 7 deletions hass_nabucasa/cloud_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
Any,
Awaitable,
Callable,
Concatenate,
Coroutine,
ParamSpec,
TypeVar,
)
from aiohttp import ClientResponse
Expand All @@ -16,6 +19,7 @@

_LOGGER = logging.getLogger(__name__)

P = ParamSpec("P")
T = TypeVar("T")

if TYPE_CHECKING:
Expand All @@ -28,27 +32,36 @@ def _do_log_response(resp: ClientResponse) -> None:
meth("Fetched %s (%s)", resp.url, resp.status)


def _check_token(func: Callable[..., Awaitable[T]]) -> Callable[..., Awaitable[T]]:
def _check_token(
func: Callable[Concatenate[Cloud[_ClientT], P], Awaitable[T]]
) -> Callable[Concatenate[Cloud[_ClientT], P], Coroutine[Any, Any, T]]:
"""Decorate a function to verify valid token."""

@wraps(func)
async def check_token(cloud: Cloud[_ClientT], *args: Any) -> T:
async def check_token(
cloud: Cloud[_ClientT],
*args: P.args,
**kwargs: P.kwargs,
) -> T:
"""Validate token, then call func."""
await cloud.auth.async_check_token()
return await func(cloud, *args)
return await func(cloud, *args, **kwargs)

return check_token


def _log_response(
func: Callable[..., Awaitable[ClientResponse]]
) -> Callable[..., Awaitable[ClientResponse]]:
func: Callable[Concatenate[P], Awaitable[ClientResponse]]
) -> Callable[Concatenate[P], Coroutine[Any, Any, ClientResponse]]:
"""Decorate a function to log bad responses."""

@wraps(func)
async def log_response(*args: Any) -> ClientResponse:
async def log_response(
*args: P.args,
**kwargs: P.kwargs,
) -> ClientResponse:
"""Log response if it's bad."""
resp = await func(*args)
resp = await func(*args, **kwargs)
_do_log_response(resp)
return resp

Expand Down