相关疑难解决方法(0)

具有自我类型的通用协议中的类方法,mypy类型检查失败

一点背景,我基本上需要定义一个int包装类型,比如说MyInt(在其他一些类中),以及另一个Interval可以接受MyInt对象以及其他类型对象的泛型类型.由于不可接受的类型Interval不属于整洁的层次结构,我认为这将是实验的完美用例Protocol,在我的情况下需要几个方法和几个@classmethods.所有方法都返回一个"自我类型",即MyInt.my_method返回一个MyInt.这是一个MCVE:

from dataclasses import dataclass
from typing import Union, ClassVar, TypeVar, Generic, Type

from typing_extensions import Protocol


_P = TypeVar('_P', bound='PType')
class PType(Protocol):
    @classmethod
    def maximum_type_value(cls: Type[_P]) -> _P:
        ...
    @classmethod
    def minimum_type_value(cls: Type[_P]) -> _P:
        ...
    def predecessor(self: _P) -> _P:
        ...
    def successor(self: _P) -> _P:
        ...

@dataclass
class MyInteger:
    value: int
    _MAX: ClassVar[int] = 42
    _MIN: ClassVar[int] = -42 …
Run Code Online (Sandbox Code Playgroud)

python class-method structural-typing python-3.x mypy

8
推荐指数
1
解决办法
608
查看次数

使用描述符进行类型提示

这个拉取请求中,似乎添加了对描述符的类型提示支持。

但是,似乎从未发布过最终的“正确”使用示例,也似乎从未将任何文档添加到typing模块Mypy 中

看起来像的正确用法是像这样

from typing import TypeVar

T = TypeVar('T')
V = TypeVar('V')


class classproperty():
    def __init__(self, getter: Callable[[Type[T]], V]) -> None:
        self.getter = getter

    def __get__(self, instance: Optional[T], owner: Type[T]) -> V:
        return self.getter(owner)


def forty_two(cls: Type) -> int:
    return 42


class C:
    forty_two: int = classproperty(forty_two)
Run Code Online (Sandbox Code Playgroud)

这似乎合乎逻辑,但我不知道这是否真的是正确的做事方式。

有没有这方面的文件?或者实际适用于合并版本的完整示例?

python type-hinting python-3.x python-descriptors mypy

8
推荐指数
1
解决办法
1145
查看次数