How to type hint a variadic function that returns its arguments in Python

Viewed 166

I'm trying to create a function that can be used as an annotation (to later inspect the function and do stuff with the expected return values...)

def WillReturn(*kwargs):
    # dark magic
    return kwargs

Question is: how do I annotate WillReturn in such a way that the type hinter will give the following warnings?

def MyFunction(a, b, c) -> WillReturn(int=1, str='yo'):
    return (123, 
            1.2,  # error! expects a str at position #1
            None) # error! expects two values

Idea 1:

This would do the trick but is not quite scalable:

A,B,C,D,E,F = map(typing.TypeVar, 'ABCDEF')
@typing.overload
def WillReturn(A) -> A: ...
@typing.overload
def WillReturn(A,B) -> (A,B): ...
@typing.overload
def WillReturn(A,B,C) -> (A,B,C): ...

# and so on and so forth

Idea 2:

subclass from typing.Tuple or use _VariadicGenericAlias directly, but I'm not entirely sure if this is the intended usage of either object.

0 Answers
Related