Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
871 views
in Technique[技术] by (71.8m points)

typing - Python mypy type error with Union of callable and list of callable converted to list of callable

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be "fixed" by using isinstance instead (at least in Pycharm's implementation of the static checker):

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

MyPy is stricter than Pycharm, but I'd expect it to fix it for MyPy as well. if type(x) is y seems to throw type checkers.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...