Type annotations for *args and **kwargs
<p>I'm trying out Python's type annotations with abstract base classes to write some interfaces. Is there a way to annotate the possible types of <code>*args</code> and <code>**kwargs</code>?</p>

<p>For example, how would one express that the sensible arguments to a function are either an <code>int</code> or two <code>int</code>s? <code>type(args)</code> gives <code>Tuple</code> so my guess was to annotate the type as <code>Union[Tuple[int, int], Tuple[int]]</code>, but this doesn't work.</p>

<pre><code>from typing import Union, Tuple

def foo(*args: Union[Tuple[int, int], Tuple[int]]):
    try:
        i, j = args
        return i + j
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))
</code></pre>

<p>Error messages from mypy:</p>

<pre><code>t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
</code></pre>

<p>It makes sense that mypy doesn't like this for the function call because it expects there to be a <code>tuple</code> in the call itself. The addition after unpacking also gives a typing error that I don't understand.</p>

<p>How does one annotate the sensible types for <code>*args</code> and <code>**kwargs</code>?</p>