Odexios Odexios -3 years ago 105
Python Question

Python type hints and `*args`

Assume I have a function like this:

def foo(*args):
for x in args:
print(x)


and let's say I want to say that all the elements of
args
are
int
; what is the right way to express it as of PEP 0484? Should I do something like

from typing import Tuple


def foo(*args: Tuple[int, ...]) -> None:
for x in args:
print(x)


or something like

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


or something else entirely?

In particular, I'm trying to use type hints effectively in PyCharm, and none of the solutions I've thought of seems to help PyCharm understand that
x
should be an
int
.

Answer Source

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)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download