【问题标题】:Python: typing a generic function that receives a type and returns an instance of that typePython:输入一个接收类型并返回该类型实例的泛型函数
【发布时间】:2021-08-13 13:09:07
【问题描述】:
我想在 Python 函数中添加类型,该函数将类型作为参数(实际上是特定类的子类型),并返回该类型的实例。考虑一个将特定类型作为参数的工厂,例如:
T = TypeVar('T', bound=Animal)
def make_animal(animal_type: Type[T]) -> T: # <-- what should `Type[T]` be?
return animal_type()
(显然这是一个非常简单的例子,但它演示了案例)
这感觉应该是可能的,但我找不到如何正确输入提示。
【问题讨论】:
标签:
python
generics
type-hinting
【解决方案1】:
这样的事情怎么样?
from __future__ import annotations
from typing import Type
class Animal:
...
def make_animal(animal_type: Type[Animal]) -> Animal:
return animal_type()
【解决方案2】:
不确定您的问题是什么,您发布的代码是完全有效的 Python 代码。 typing.Type 正是你想要的:
from typing import Type, TypeVar
class Animal: ...
class Snake(Animal): ...
T = TypeVar('T', bound=Animal)
def make_animal(animal_type: Type[T]) -> T:
return animal_type()
reveal_type(make_animal(Animal)) # Revealed type is 'main.Animal*'
reveal_type(make_animal(Snake)) # Revealed type is 'main.Snake*'
在 mypy-play 上查看 mypy 输出。