Python mypy 类型错误,可调用联合和可调用列表转换为可调用列表

时间:2021-02-05 16:39:18

标签: python typing mypy

参数 hook 可以是函数或函数列表。如果它是一个函数,我会将它转换为一个列表,以便稍后可以假设它是一个列表。

HookType = Union[Callable[[str], str], List[Callable[[str], str]]]

...

def __init__(
    ...
    hook: HookType = [],
):
    ...
    if type(hook) is not list:
        hook = [hook]
    self.hook: List[Callable[[str], str]] = hook

运行 mypy 时出现以下错误:

foo.py:54: error: List item 0 has incompatible type "Union[Callable[[str], str], List[Callable[[str], str]]]"; expected "Callable[[str], str]"
foo.py:57: error: Incompatible types in assignment (expression has type "Union[Callable[[str], str], List[Callable[[str], str]]]", variable has type "List[Callable[[str], str]]")
Found 4 errors in 1 file (checked 20 source files)

mypy 不检测检查 hook 类型的条件吗?

我还应该提到我启用了一些 mypy 选项:

[mypy]
check_untyped_defs = true
disallow_incomplete_defs = true

1 个答案:

答案 0 :(得分:0)

这可以通过使用 isinstance 来“修复”(至少在 Pycharm 的静态检查器实现中):

if not isinstance(hook, list):
    hook = [hook]

MyPy 比 Pycharm 更严格,但我希望它也能针对 MyPy 修复它。 if type(x) is y 似乎会抛出类型检查器。