Python type hints and `*args` Python type hints and `*args` python-3.x python-3.x

Python type hints and `*args`


According to PEP-484:

Arbitrary argument lists can as well be type annotated, so that the definition:

def foo(*args: str, **kwds: int): ...

is acceptable and it means that, e.g., all of the following represent function calls with valid types of arguments:

foo('a', 'b', 'c')foo(x=1, y=2)foo('', z=0)

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].

The correct way to annotate the foo function from your example is:

def foo(*args: int) -> None:    for x in args:        print(x)

In Python 2:

def foo(*args):    # type: (*int) -> None    for x in args:        print(x)


You should have a look at the docstrings. PyCharm allows you to define your arguments in docstrings, with or without the types. If you define the types, the hints will take into consideration the type of the arguments.

def foo(*args):    """    General information about foo    :param [int] args: info about args    """    for x in args:        print(x)