Tips such as Python and `* args`

Suppose I have a function like this:

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

and say, I want to say that all elements argsare equal int; What is the correct way to express this as 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?

In particular, I'm trying to make good use of type hints in PyCharm, and none of the solutions that I thought of seems to help PyCharm figure out what it xshould be int.

+4
source share
2 answers

According to PEP-484 :

Arbitrary argument lists can also be annotated by type, so the definition is:

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

, , , , :

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

foo args Tuple[str, ...], kwds - Dict[str, int].

foo :

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

Python 2:

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

. PyCharm docstrings, . , .

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

    for x in args:
        print(x)
+1

Source: https://habr.com/ru/post/1617623/


All Articles