The argument hook
can either be a function or a list of function. If it's a function, I convert it to a list so I can assume it's a list later.
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
When I run mypy
I get the following error:
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)
Doesn't mypy
detect the condition which checks the type of hook
?
I should also mention that I enabled a few mypy options:
[mypy]
check_untyped_defs = true
disallow_incomplete_defs = true
question from:
https://stackoverflow.com/questions/66067128/python-mypy-type-error-with-union-of-callable-and-list-of-callable-converted-to 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…