相关疑难解决方法(0)

输入*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))
Run Code Online (Sandbox Code Playgroud)

来自mypy的错误消息:

t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]") …
Run Code Online (Sandbox Code Playgroud)

python typing typechecking type-hinting

99
推荐指数
7
解决办法
3万
查看次数

标签 统计

python ×1

type-hinting ×1

typechecking ×1

typing ×1