问题:* args和** kwargs的类型注释

我正在尝试使用具有抽象基类的Python类型注释来编写一些接口。有没有一种方法来注释可能的类型*args**kwargs

例如,如何表达一个函数的明智参数是一个int或两个inttype(args)给出,Tuple所以我的猜测是将类型注释为Union[Tuple[int, int], Tuple[int]],但这是行不通的。

from typing import Union, Tuple

def foo(*args: Union[Tuple[int, int], Tuple[int]]):
    try:
        i, j = args
        return i + j
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))

来自mypy的错误消息:

t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"

Mypy不喜欢此函数调用是有道理的,因为它希望tuple调用本身中包含a。解压后的附加内容还会产生我不理解的输入错误。

一个人如何诠释明智的类型*args**kwargs

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 **kwargs?

For example, how would one express that the sensible arguments to a function are either an int or two ints? type(args) gives Tuple so my guess was to annotate the type as Union[Tuple[int, int], Tuple[int]], but this doesn’t work.

from typing import Union, Tuple

def foo(*args: Union[Tuple[int, int], Tuple[int]]):
    try:
        i, j = args
        return i + j
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))

Error messages from mypy:

t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"

It makes sense that mypy doesn’t like this for the function call because it expects there to be a tuple in the call itself. The addition after unpacking also gives a typing error that I don’t understand.

How does one annotate the sensible types for *args and **kwargs?


回答 0

对于可变位置参数(*args)和可变关键字参数(**kw),您只需要为一个这样的参数指定期望值。

在“ 类型提示” PEP 的“ 任意参数列表”和“默认参数值”部分中:

任意参数列表也可以类型注释,以便定义:

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

是可以接受的,这意味着,例如,以下所有内容均代表带有有效参数类型的函数调用:

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

因此,您需要像这样指定您的方法:

def foo(*args: int):

但是,如果您的函数只能接受一个或两个整数值,则完全不应使用*args,请使用一个显式的位置参数和第二个关键字参数:

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

现在,您的函数实际上仅限于一个或两个参数,并且如果指定,则两个参数都必须为整数。*args 始终表示0或更大,并且不能由类型提示限制为更特定的范围。

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.


回答 1

正确的方法是使用 @overload

from typing import overload

@overload
def foo(arg1: int, arg2: int) -> int:
    ...

@overload
def foo(arg: int) -> int:
    ...

def foo(*args):
    try:
        i, j = args
        return i + j
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

print(foo(1))
print(foo(1, 2))

请注意,不要@overload在实际实现中添加注释或键入注释,后者必须排在最后。

您需要同时拥有typingmypy和mypy 的新版本才能在存根文件之外获得对@overload的支持。

您还可以使用此方法以明确表明哪些参数类型与哪种返回类型相对应的方式改变返回的结果。例如:

from typing import Tuple, overload

@overload
def foo(arg1: int, arg2: int) -> Tuple[int, int]:
    ...

@overload
def foo(arg: int) -> int:
    ...

def foo(*args):
    try:
        i, j = args
        return j, i
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

print(foo(1))
print(foo(1, 2))

The proper way to do this is using @overload

from typing import overload

@overload
def foo(arg1: int, arg2: int) -> int:
    ...

@overload
def foo(arg: int) -> int:
    ...

def foo(*args):
    try:
        i, j = args
        return i + j
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

print(foo(1))
print(foo(1, 2))

Note that you do not add @overload or type annotations to the actual implementation, which must come last.

You’ll need a newish version of both typing and mypy to get support for @overload outside of stub files.

You can also use this to vary the returned result in a way that makes explicit which argument types correspond with which return type. e.g.:

from typing import Tuple, overload

@overload
def foo(arg1: int, arg2: int) -> Tuple[int, int]:
    ...

@overload
def foo(arg: int) -> int:
    ...

def foo(*args):
    try:
        i, j = args
        return j, i
    except ValueError:
        assert len(args) == 1
        i = args[0]
        return i

print(foo(1))
print(foo(1, 2))

回答 2

作为上一个答案的简短补充,如果您要在Python 2文件上使用mypy并且需要使用注释来添加类型而不是注释,则需要分别为args和和分别为类型kwargs加上前缀:***

def foo(param, *args, **kwargs):
    # type: (bool, *str, **int) -> None
    pass

mypy将其视为与以下Python 3.5版本相同foo

def foo(param: bool, *args: str, **kwargs: int) -> None:
    pass

As a short addition to the previous answer, if you’re trying to use mypy on Python 2 files and need to use comments to add types instead of annotations, you need to prefix the types for args and kwargs with * and ** respectively:

def foo(param, *args, **kwargs):
    # type: (bool, *str, **int) -> None
    pass

This is treated by mypy as being the same as the below, Python 3.5 version of foo:

def foo(param: bool, *args: str, **kwargs: int) -> None:
    pass

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。