Python:输入一个接收类型并返回该类型实例的通用函数

she*_*ron 11 python generics type-hinting

我想向一个 Python 函数添加类型,该函数接受类型作为参数(实际上是特定类的子类型),并返回该类型的实例。想象一个接受特定类型作为参数的工厂,例如:

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

def make_animal(animal_type: Type[T]) -> T:  # <-- what should `Type[T]` be?
    return animal_type()
Run Code Online (Sandbox Code Playgroud)

(显然这是一个非常简单的例子,但它演示了这种情况)

这感觉应该是可能的,但我找不到如何正确地键入提示。

Zec*_* Hu 12

不确定你的问题是什么,你发布的代码是完全有效的 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*'
Run Code Online (Sandbox Code Playgroud)

请参阅mypy-play上的 mypy 输出。