【问题标题】:Python how to define type hint for union of all subclassesPython如何为所有子类的联合定义类型提示
【发布时间】:2021-12-09 00:33:24
【问题描述】:

假设我有一个在递归/树层次结构中有多个子类的类:

class Animal:
    pass
class Cat(Animal):
    pass
class HouseCat(Cat):
    pass

我有一个函数,可以根据某些条件创建这些类的实例:

from typing import Union
def creator(condition) -> Union[Animal, Cat, HouseCat]:
    # for codition1
    return Animal()
    # for codition2
    return Cat()
    # ...etc...

我的问题是,如果我只使用 -> Animal: 作为返回值注释,PyCharm 会显示这样的警告:

my_list: List[Cat] = []
obj = creator(...)
my_list.append(obj)  # <-- Expected type 'Cat' (matched generic type '_T'), got 'Animal' instead

有没有办法定义类型提示而不是手动为所有子类编写Union?

【问题讨论】:

  • -&gt; Animal 因为子类会正确输入
  • Type[Animal] 会做到的 :)
  • 抱歉,编辑了问题,在 PyCharm 中添加了我的问题

标签: python union subclass typing


【解决方案1】:

您可以使用TypeVar 构造来编写带边界的代码:

from typing import TypeVar, List


class Animal:
    pass


class Cat(Animal):
    pass


class HouseCat(Cat):
    pass


A = TypeVar('A', bound=Animal)


def creator() -> A:
    pass


my_list: List[Cat] = []
obj = creator()
my_list.append(obj)

https://docs.python.org/3/library/typing.html#typing.TypeVar

【讨论】:

  • 谢谢,这行得通。
猜你喜欢
  • 2017-01-13
  • 2021-08-14
  • 2011-03-31
  • 2016-08-17
  • 2021-05-30
  • 2022-08-18
  • 2020-04-24
  • 2021-06-06
相关资源
最近更新 更多