Ale*_*lex 1 python typing dependent-type mypy
对于以下示例,mypy
返回错误:
错误:赋值中的类型不兼容(表达式类型为“A”,变量类型为“A1”)
from typing import Type
class A:
pass
class A1(A):
pass
class A2(A):
pass
def fun(A_type: Type[A]) -> A:
if A_type == A1:
return A1()
else:
return A2()
a1: A1 = fun(A1)
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想做的是在以下签名中强制执行依赖项fun
:
def fun(A_type: Type[A]) -> A_type
Run Code Online (Sandbox Code Playgroud)
这可能吗; 如果没有,推荐什么(注意:我希望它适用于尚未定义的子类A
,所以我认为我不能使用overload
装饰器)?我最好的选择只是使用cast
吗?
使用带有边界的 TypeVar:
https://mypy.readthedocs.io/en/latest/generics.html#type-variables-with-upper-bounds
from typing import Type, TypeVar
class A:
pass
class A1(A):
pass
class A2(A):
pass
T_A = TypeVar('T_A', bound='A')
def fun(A_type: Type[T_A]) -> T_A:
if A_type == A1:
r1 = A1()
assert isinstance(r1, A_type)
return r1
else:
r2 = A2()
assert isinstance(r2, A_type)
return r2
a1: A1 = fun(A1)
a2: A2 = fun(A2)
print("winner winner chicken dinner")
Run Code Online (Sandbox Code Playgroud)
类型检查干净并运行而不会失败任何类型断言:
C:\test\python>mypy polymorph.py
Success: no issues found in 1 source file
C:\test\python>python polymorph.py
winner winner chicken dinner
Run Code Online (Sandbox Code Playgroud)
在这个例子中,类型T_A
需要是 的子类A
,但它是一个特定的类型,并且类型fun
要求它返回它作为参数接收的相同类型。
不幸的是,静态类型检查是不是很绑定类型足够聪明的,除非你加在里面运行时断言(可能有一些方法来做到这一点更好地与Generic
类型,但它躲开我)。