微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用MyPy重载__init__方法以调整获取器的返回值?

如何解决如何使用MyPy重载__init__方法以调整获取器的返回值?

假设我有一个这样的类(伪代码,请忽略奇数数据库结构):

class Blog():
    title = Stringproperty()
    comments = StringProperty(repeated=True)

我要键入检查StringProperty,以使Blog().title返回str类型,而Blog().comments返回List[str]类型。 MyPy提到通过dynamically typing the __init__方法可以实现类似的功能

这是我尝试过的:

U = TypeVar('U',bound=StringProperty)
V = TypeVar('V',bound=StringProperty)

class StringProperty(Property[T]):
    @overload
    def __init__(self: StringProperty[U],repeated: Literal[False]=False,**kwargs) -> None: ...

    @overload
    def __init__(self: StringProperty[V],repeated: Literal[True]=True,**kwargs) -> None: ...

    @overload
    def __get__(self: StringProperty[U],instance,cls) -> str: ...
    
    @overload
    def __get__(self: StringProperty[V],cls) -> List[str]: ...
    
    def __set__(self,value: Optional[Union[str,List[str]]]) -> None: ...

但是,这引发了一个错误,即第二个__get__类型签名将永远不会被匹配。如何设置MyPy以通过StringProperty.__get__属性repeated还是True属性来动态地知道False方法的返回值?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。