繁体   English   中英

推断 Generic 子类的 Type 自身为 Type

[英]Infer Type of a Generic subclass as having itself as Type

我正在为外部 ORM 库制作存根,但我遇到了一个我不知道如何克服的问题。 因此,下面的示例在技术上通过了 mypy 检查,但仅在期望库用户在 class 声明期间繁琐地重复自己之后。

# Library stubs:
from typing import Generic, TypeVar, Type, Any, Optional
from collections.abc import Collection, Sequence
from abc import ABC


T = TypeVar('T', bound='BaseItem')
K = TypeVar('K')

class ItemSet(Generic[K]):
    def get_or_none(self, **kwargs: Any) -> Optional[K]: ...
    def first(self) -> K: ...
    def all(self) -> Collection[K]: ...
    def order_by(self, *args: Any) -> Sequence[K]: ...

class BaseItem(ABC, Generic[T]):
    @classmethod
    def set(cls: Type[T]) -> ItemSet[T]: ...

# User's model:
from library import BaseItem


class FooItem(BaseItem['FooItem']):
    name: str

class BarItem(BaseItem['BarItem']):
    size: float

class BazItem(BaseItem['BazItem']):
    id_: int

reveal_type(FooItem.set())
reveal_type(FooItem.set().all())

这将生成此 output:

main.py:32: note: Revealed type is "__main__.ItemSet[__main__.FooItem*]"
main.py:33: note: Revealed type is "typing.Collection[__main__.FooItem*]"

这正是您所期望的,但这仅适用于用户必须将 class 名称作为每个class 定义的类型传递。 类型的省略导致它具有Any类型

class FooItem(BaseItem):
    name: str
main.py:32: note: Revealed type is "__main__.ItemSet[Any]"
main.py:33: note: Revealed type is "typing.Collection[Any]"

所以我的问题是如何使这种类型推断对用户不可见?

这是因为您将其设为通用 class,它不应该是通用 class ,本质上是通用 function。 只需使用以下内容:

from typing import Generic, TypeVar, Type, Any, Optional
from collections.abc import Collection, Sequence
from abc import ABC


T = TypeVar('T', bound='BaseItem')
K = TypeVar('K')

class ItemSet(Generic[K]):
    def get_or_none(self, **kwargs: Any) -> Optional[K]: ...
    def first(self) -> K: ...
    def all(self) -> Collection[K]: ...
    def order_by(self, *args: Any) -> Sequence[K]: ...

class BaseItem(ABC):
    @classmethod
    def set(cls: Type[T]) -> ItemSet[T]: ...


class FooItem(BaseItem):
    name: str

class BarItem(BaseItem):
    size: float

class BazItem(BaseItem):
    id_: int

reveal_type(FooItem.set())
reveal_type(FooItem.set().all())

这是 MyPy 的想法(注意,为了简洁起见,我将所有内容都放在一个名为 test.py 的模块中):

(py39) Juans-MacBook-Pro:~ juan$ mypy test.py
test.py:29: note: Revealed type is "test.ItemSet[test.FooItem*]"
test.py:30: note: Revealed type is "typing.Collection[test.FooItem*]"

请注意,此特定情况在 PEP-484 规范中已解决

请注意,有一个 PEP 可以删除TypeVar样板:

https://www.python.org/dev/peps/pep-0673/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM