微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决Python 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]]]"; expected "Callable[[str],str]"
foo.py:57: error: Incompatible types in assignment (expression has type "Union[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

解决方法

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

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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。