问题描述
我正在查看typeshed
的来源,发现它在pathlib.pyi
中执行以下操作:
_P = TypeVar('_P',bound=PurePath)
...
class PurePath(_PurePathBase): ...
对于基类,我有一个类似的情况,该基类从__new__
返回一个子类(类似于Path
),因此类型注释也将相似。但是,为下面定义的类定义bound
关键字会解析为 NameError ,因为名称尚未解析(正如我所期望的那样;由于{{ 1}}源。
typeshed
from abc import ABC
from typing import Type
from typing import TypeVar
from foo.interface import SomeInterface
_MT = TypeVar('_MT',bound=MyBaseClass)
class MyBaseClass(SomeInterface,ABC):
def __new__(cls: Type[_MT],var: int = 0) -> _MT:
if var == 1:
return object.__new__(FirstSubClass)
return object.__new__(cls)
class FirstSubClass(MyBaseClass): pass
如何摆脱困境?这对我的打字非常理想,否则我必须这样做:
typeshed
我所有的短毛猫警告都得到了满足(_MT = TypeVar('_MT',covariant=True,bound=SomeInterface)
)...
比较合适的情况是typing a factory method,因为我将"expected type _MT,got object instead"
作为工厂使用,类似于__new__
的工作方式,并且如上所述here。不过,很高兴知道Path
如何在不使用字符串的情况下完成对typeshed
的前向引用。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)