参数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发布于 2021-02-06 00:51:28
这可以通过使用isinstance来“修复”(至少在Pycharm的静态检查器实现中):
if not isinstance(hook, list):
hook = [hook]MyPy比Pycharm更严格,但我希望它也能为MyPy修复它。if type(x) is y似乎抛出了类型检查器。
https://stackoverflow.com/questions/66067128
复制相似问题