Skip to content

Instantly share code, notes, and snippets.

@Calcifer777
Created February 7, 2025 04:36
Show Gist options
  • Save Calcifer777/56ae883629b2d7d20293d0c242bb31f6 to your computer and use it in GitHub Desktop.
Save Calcifer777/56ae883629b2d7d20293d0c242bb31f6 to your computer and use it in GitHub Desktop.
pydantic_async_decorator
from functools import wraps
from typing import Any
from typing import Awaitable
from typing import Callable
from typing import TypeVar
from pydantic import BaseModel
class BaseRequest(BaseModel):
field: int
class BaseResponse(BaseModel):
field: int
T = TypeVar("T_co", bound=BaseRequest)
def async_decorator(
func: Callable[[T, Any], Awaitable[BaseResponse]],
) -> Callable[[T, Any], Awaitable[int | BaseResponse]]:
"""
Wraps an async function, making a wrapper that returns
its output or *something else* (in this case, for example purposes,
an `int`).
Both `T` and the return type (`BaseResponse`) need to
be concrete Pydantic types, otherwise type inference does
not work.
"""
@wraps(func)
async def wrapper(req: T, *args, **kwargs):
out = await func(req, *args, **kwargs)
# do things
return -1
return wrapper
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment