using Python 3.11 and Mypy 1.7.
我正在try 正确地键入hint方法,该方法接受一个类作为参数,带有一个默认值,并返回该类的一个实例.作为参数传递的类必须是特定基类的子类. 我该怎么做呢? 我试着这样用type variable with upper bound:
from typing import TypeVar
class BaseClass: pass
class ImplClass(BaseClass): pass
T = TypeVar("T", bound=BaseClass)
def method(return_type: type[T] = ImplClass) -> T:
return return_type()
但Mypy抱怨道:
scratch_10.py: note: In function "method":
scratch_10.py:9:35: error: Incompatible default for argument "return_type" (default has type "type[ImplClass]", argument has type "type[T]") [assignment]
def method(return_type: type[T] = ImplClass) -> T:
^~~~~~~~~
但据我所知,这个错误是错误的,因为缺省的ImplClass
是BaseClass
的子类,这是T
的上界,所以它尊重类型约束.
请注意,移除上限值无济于事:
T = TypeVar("T") #no upperbound this time
def method(return_type: type[T] = ImplClass) -> T:
return return_type()
(相同的错误消息)
但删除缺省值并以ImplClass
作为参数显式调用method
的效果没有任何问题:
def method(return_type: type[T]) -> T: # no default value this time
return return_type()
method(ImplClass)
成功,在1个源文件中未发现问题
所以我不明白为什么mypy
抱怨缺省值,而不是抱怨具有完全相同的值的实际参数.这是mypy
的假阳性,还是我做错了什么?