Skip to content

Instantly share code, notes, and snippets.

@jdoiwork
Created April 17, 2021 18:50
Show Gist options
  • Select an option

  • Save jdoiwork/653381c447f294371bbf5aac0ca7534a to your computer and use it in GitHub Desktop.

Select an option

Save jdoiwork/653381c447f294371bbf5aac0ca7534a to your computer and use it in GitHub Desktop.
python decorator typing hint
from typing import Any, Callable, TypeVar, Tuple, cast
F = TypeVar('F', bound=Callable[..., Any])
# A decorator that preserves the signature.
def my_decorator(func: F) -> F:
def wrapper(*args, **kwds):
print("Calling", func)
return func(*args, **kwds)
return cast(F, wrapper)
def my_decorator2(x: Any) -> Callable[[F], F]:
def decorator(func: F) -> F:
def wrapper(*args, **kwds):
print(x)
print("Calling", func)
return func(*args, **kwds)
return wrapper
return cast(Callable[[F], F], decorator)
# A decorated function.
@my_decorator
def foo(a: int) -> str:
return str(a)
a = foo(12)
@my_decorator2(30)
def baa(a: int) -> str:
return str(a)
foo('x') # Type check error: incompatible type "str"; expected "int"
baa('y')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment