我正在使用mypy,遇到了意想不到的行为.Mypy错误地推断出预期类型的类型
from typing import Generic, TypeVar, Callable, reveal_type
S1 = TypeVar('S1')
F1 = TypeVar('F1')
I = TypeVar('I')
class Node(Generic[I, S1, F1]):
def __init__(self, callback: Callable[[I], S1 | F1]):
self.callback: Callable[[I], S1 | F1] = callback
class Succ1:
...
class Fail1:
...
def func1(_: str) -> Succ1 | Fail1:
return Succ1()
n1 = Node(func1)
res1 = n1.callback("str")
reveal_type(n1)
% mypy isolated_example2.py
isolated_example2.py:25: error: Need type annotation for "n1" [var-annotated]
isolated_example2.py:25: error: Argument 1 to "Node" has incompatible type "Callable[[str], Succ1 | Fail1]"; expected "Callable[[str], Never]" [arg-type]
isolated_example2.py:27: note: Revealed type is "isolated_example2.Node[builtins.str, Any, Any]"
Found 2 errors in 1 file (checked 1 source file)
我不期望类型Callable[[stat],Never],并且认为没有理由这样认为.可能是什么问题?
mypy==1.9.0
Python 3.12.3
这是一个更大问题的一部分,但我试图将其分成独立的块,以更好地理解流程
UPD:看起来像Unioning TypVar中的一个问题.这是重现错误的最小示例
from typing import TypeVar
S1 = TypeVar('S1')
F1 = TypeVar('F1')
def func(arg: S1 | F1):
return arg
func(None)