Skip to content

Python Code Type Hints Snippets

Published: at 08:35 AM

Typst

Table of Contents

Open Table of Contents

Type Hints for decorator that wrap async functions

def decorator_f[**P, T](func: Callable[P, Awaitable[T]]) -> Callable[P, Awaitable[T]]:
    @wraps(func)
    async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
        needed_parameters: NeededParameters | None = None

        for arg in args:
            if isinstance(arg, NeededParameters):
                needed_parameters = arg
                break

        if needed_parameters is None:
            needed_parameters = kwargs.get('needed_parameters')

        if needed_parameters is None:
            raise ValueError("No NeededParameters provided")

        # ...

        return await func(*args, **kwargs)

Annotate a function to provide information like Auth

def require_auth(authorization: Annotated[str | None, Header()] = None) -> None: 
    if authorization is None:
        raise HTTPException(status_code=401, detail="Authorization header missing")

    if not authorization.startswith("Bearer "):
        raise HTTPException(status_code=401, detail="Invalid authorization format")

    token = authorization[7:]

    verify_result = auth_provider.verify_token(token)

    if verify_result.not.passed:
        raise HTTPException(status_code=401, detail="Invalid token")

and for function that need auth

@router.get("/protected-endpoint")
def need_auth(
    _: Anotated[None, Depends(require_auth)],
) -> ...:
    ...

or you could add to the api

@router.get("/protected-endpoint", dependencies=[Depends(require_auth)])
def need_auth() -> ...:
    ...

Compare to using decorator, using annotated is more convient, and easy to add type hints.