为什么 mypy 不理解这个对象实例化?

jpm*_*los 6 python type-hinting abstract-base-class mypy python-typing

我正在尝试定义一个类,该类将另一个类作为属性_model并将实例化该类的对象。

from abc import ABC
from typing import Generic, TypeVar, Any, ClassVar, Type

Item = TypeVar("Item", bound=Any)


class SomeClass(Generic[Item], ABC):
    _model: ClassVar[Type[Item]]

    def _compose_item(self, **attrs: Any) -> Item:
        return self._model(**attrs)
Run Code Online (Sandbox Code Playgroud)

self._model(**attrs)我认为返回 , 的实例应该是显而易见的Item,因为_model被显式声明为Type[Item]并被attrs声明为Dict[str, Any]

但我从中得到的mypy 0.910是:

test.py: note: In member "_compose_item" of class "SomeClass":
test.py:11: error: Returning Any from function declared to return "Item"
            return self._model(**attrs)
            ^
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

Ale*_*ood 5

MyPy 有时对于类的类型有点有趣。您可以通过指定as (毕竟,这不是谎言而不是 来解决这个问题_modelCallable[..., Item]Type[Item]

from abc import ABC
from typing import Generic, TypeVar, Any, ClassVar, Callable

Item = TypeVar("Item")


class SomeClass(Generic[Item], ABC):
    _model: ClassVar[Callable[..., Item]]

    def _compose_item(self, **attrs: Any) -> Item:
        return self._model(**attrs)
Run Code Online (Sandbox Code Playgroud)