Skip to content

Instantly share code, notes, and snippets.

@laundmo
Created June 20, 2024 14:51
Show Gist options
  • Save laundmo/a5a007d99b0f087079346f3479afe7e9 to your computer and use it in GitHub Desktop.
Save laundmo/a5a007d99b0f087079346f3479afe7e9 to your computer and use it in GitHub Desktop.
Copy a functions/methods signature for typing without specifying each individual argument type
from typing import Callable, ParamSpec, TypeVar, cast
P = ParamSpec("P")
T = TypeVar("T")
def copy_sig(source_func: Callable[P, T]) -> Callable[[Callable[..., T]], Callable[P, T]]:
"""Decorator to copy the function signature from source_func
Especially useful when overwriting methods with many arguments
CAREFUL: Only works towards the outside. Inside the function the types won't show up.
@copy_sig(source_func)
def other_func(*args, **kwargs):
...
"""
def return_func(func: Callable[..., T]) -> Callable[P, T]:
return cast(Callable[P, T], func)
return return_func
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment