Created
June 20, 2024 14:51
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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