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 *args
and **kwargs
?
For example, how would one express that the sensible arguments to a function are either an int
or two int
s? type(args)
gives Tuple
so my guess was to annotate the type as Union[Tuple[int, int], Tuple[int]]
, but this doesn't work.
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))
Error messages from mypy:
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]]"
It makes sense that mypy doesn't like this for the function call because it expects there to be a tuple
in the call itself. The addition after unpacking also gives a typing error that I don't understand.
How does one annotate the sensible types for *args
and **kwargs
?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…