Type annotations for *args and **kwargs

后端 未结 4 1548
無奈伤痛
無奈伤痛 2020-12-04 09:05

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

4条回答
  •  孤城傲影
    2020-12-04 09:31

    For variable positional arguments (*args) and variable keyword arguments (**kw) you only need to specify the expected value for one such argument.

    From the Arbitrary argument lists and default argument values section of the Type Hints PEP:

    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)
    

    So you'd want to specify your method like this:

    def foo(*args: int):
    

    However, if your function can only accept either one or two integer values, you should not use *args at all, use one explicit positional argument and a second keyword argument:

    def foo(first: int, second: Optional[int] = None):
    

    Now your function is actually limited to one or two arguments, and both must be integers if specified. *args always means 0 or more, and can't be limited by type hints to a more specific range.

提交回复
热议问题