Python mypy type error with Union of callable and list of callable converted to list of callable
Python mypy type error with Union of callable and list of callable converted to list of callable
参数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
这可以通过使用 isinstance
来“修复”(至少在 Pycharm 的静态检查器实现中):
if not isinstance(hook, list):
hook = [hook]
MyPy 比 Pycharm 更严格,但我希望它也能为 MyPy 修复它。 if type(x) is y
似乎会抛出类型检查器。
参数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
这可以通过使用 isinstance
来“修复”(至少在 Pycharm 的静态检查器实现中):
if not isinstance(hook, list):
hook = [hook]
MyPy 比 Pycharm 更严格,但我希望它也能为 MyPy 修复它。 if type(x) is y
似乎会抛出类型检查器。