Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy type signature from another function

Imagine I have a set of functions like below. foo has a lot of arguments of various types, and bar passes all its arguments to that other function. Is there any way to make mypy understand that bar has the same type as foo without explicitly copying the whole argument list?

def foo(a: int, b: float, c: str, d: bool, *e: str, f: str = "a", g: str = "b") -> str:
    ...

def bar(*args, **kwargs):
    val = foo(*args, **kwargs)
    ...
    return val
like image 239
Kyuuhachi Avatar asked Jan 13 '20 13:01

Kyuuhachi


1 Answers

There's been a lot of discussion about adding this feature here. For the straightforward case of passing all arguments you can use the recipe from this comment:

F = TypeVar('F', bound=Callable[..., Any])

class copy_signature(Generic[F]):
    def __init__(self, target: F) -> None: ...
    def __call__(self, wrapped: Callable[..., Any]) -> F: ...

def f(x: bool, *extra: int) -> str: ...

@copy_signature(f)
def test(*args, **kwargs):
    return f(*args, **kwargs)

reveal_type(test)  # Revealed type is 'def (x: bool, *extra: int) -> str'
like image 168
Alex Hall Avatar answered Nov 20 '22 06:11

Alex Hall