简体   繁体   English

Python:键入一个通用 function 接收一个类型并返回该类型的实例

[英]Python: typing a generic function that receives a type and returns an instance of that type

I want to add typing to a Python function that takes in a type as an argument (actually, a subtype of a specific class), and return an instance of that type.我想将类型添加到 Python function 中,它将类型作为参数(实际上是特定类的子类型),并返回该类型的实例。 Think a factory that takes in the specific type as an argument, eg:考虑一个将特定类型作为参数的工厂,例如:

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

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

(obviously this is a very simplistic example, but it demonstrates the case) (显然这是一个非常简单的例子,但它演示了案例)

This feels like something that should be possible, but I couldn't find how to properly type-hint this.这感觉应该是可能的,但我找不到如何正确输入提示。

Not sure what your question is, the code you posted is perfectly valid Python code.不确定您的问题是什么,您发布的代码是完全有效的 Python 代码。 There istyping.Type that does exactly what you want: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*'

See mypy output on mypy-play .请参阅mypy-play上的 mypy output 。

How about something like this?这样的事情怎么样?

from __future__ import annotations
from typing import Type


class Animal:
    ...


def make_animal(animal_type: Type[Animal]) -> Animal:
    return animal_type()

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

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