Skip to content

Instantly share code, notes, and snippets.

@MartinThoma
Created October 2, 2021 10:08
Show Gist options
  • Save MartinThoma/794612273b631d745d3be7cb04404910 to your computer and use it in GitHub Desktop.
Save MartinThoma/794612273b631d745d3be7cb04404910 to your computer and use it in GitHub Desktop.
from typing import Awaitable, Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def add_logging(f: Callable[P, R]) -> Callable[P, Awaitable[R]]:
async def inner(*args: P.args, **kwargs: P.kwargs) -> R:
await log_to_database()
return f(*args, **kwargs)
return inner
@add_logging
def takes_int_str(x: int, y: str) -> int:
return x + 7
await takes_int_str(1, "A") # Accepted
await takes_int_str("B", 2) # Correctly rejected by the type checker
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment