mypy error: Callable has no attribute "__get__"

mypy error: Callable has no attribute "__get__"

我有如下内容:

from typing import TypeVar, Callable, Generic, Type, Union, Optional

T = TypeVar("T")
V = TypeVar("V")

class DescClass(Generic[T, V]):
    """A descriptor."""
    def __init__(self, func: Callable[[T], V]) -> None:
        self.func = func

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

class C:
    @DescClass
    def f(self): ...

...Mypy 将 return 此错误:

test.py:12: error: "Callable[[T], Any]" has no attribute "__get__"

func 指定类型的规范方法是什么,以便 Mypy 理解它是一个描述符 (and thus always has a __get__)?

更新:"descriptor"has no hits搜索Mypy帮助的时候有点幽默

这似乎在现代 Python 和现代 mypy 上运行良好:

from typing import (
    TypeVar,
    Callable,
    Generic, 
    Type, 
    Optional,
    cast,
    Protocol
)

T_contra = TypeVar("T_contra", contravariant=True)
V = TypeVar("V")
P_co = TypeVar("P_co", covariant=True)


class DescriptorProto(Protocol[P_co, T_contra]):
    def __get__(
        self, 
        instance: Optional[T_contra], 
        owner: Type[T_contra]
    ) -> P_co:
        ...


FuncType = DescriptorProto[Callable[[], V], T_contra]


class DescClass(Generic[T_contra, V]):
    """A descriptor."""

    def __init__(self, func: Callable[[T_contra], V]) -> None:
        self.func = cast(FuncType[V, T_contra], func)

    def __get__(
        self, 
        instance: Optional[T_contra], 
        owner: Type[T_contra]
    ) -> Callable[[], V]:
        return self.func.__get__(instance, owner)


class C:
    @DescClass
    def f(self) -> None: ...