Search code examples
pythonpython-typing

How to annotate variadic parameters in Python using typing annotations?


How to annotate parameters of the variadic function?

Example:

def foo(*args):  # Each arg expected to be of type T
    ...

Are there any typing annotations for that?


Solution

  • tl;dr

    Basically args treated as a homogeneous tuple and kwds as a dictionary. You simply annotate a type being expected for each element value.

    Explanation

    Explanation arrives from quote of the PEP-484:

    In the body of function foo, the type of variable args is deduced as Tuple[str, ...] and the type of variable kwds is Dict[str, int].

    So there is no need to annotate args as whole homogeneous typed tuple but one can reduce Tuple[T, ...] to just type T.

    Same true for the keyword arguments as they deduced as Dict[str, T]

    About ellipsis in the tuple annotation

    In python documentation there is no much information about the usage of the ... a.k.a Ellipsis but PEP-484 does mention various usages of the ellipsis in typing annotations like for omitting some type annotations or default values but most interestingly there is a quote saying:

    Tuple, used by listing the element types, for example Tuple[int, int, str]. The empty tuple can be typed as Tuple[()]. Arbitrary-length homogeneous tuples can be expressed using one type and ellipsis, for example Tuple[int, ...]. (The ... here are part of the syntax, a literal ellipsis.)

    So if you omit asterisk to force passing arguments as a single tuple you need keep full annotation:

    def foo(args: Tuple[T, ...]):
        ...
    

    About various types in a homogeneous tuple

    Since homogeneous tuple means all of its elements must be of the same type then if you wish to allow several types just use a Union or even use a type alias for better readability:

    MyArg = Union[int, str, bool]
    
    def foo(*args: MyArg):
        ...