[英]Python annotate return type as the type given to function
I am giving a type to function.我正在给一个类型的功能。 The function instantiates the type for me.该函数为我实例化类型。 The type implements BaseCustomObject
but is one of many possible types.该类型实现BaseCustomObject
但它是许多可能的类型之一。
def factory(object_to_create:[T], parameter:int=1) -> [T]:
constructor_parameter = calculation(parameter)
return object_to_create(constructor_parameter)
my_custom_object_instance = factory(MyCustomObject)
How do I annotate factory
so that it is clear that it gives back whatever type I send it, and not just BaseCustomObject
?我如何注释factory
以便很明显它返回我发送的任何类型,而不仅仅是BaseCustomObject
? I prefer not to use a Union type but to have the annotation/inspection/ide understand exactly which specific type I am getting back.我不喜欢使用联合类型,而是让注释/检查/ide 准确了解我要返回的特定类型。
use a TypeVar generic type.使用 TypeVar 泛型类型。 [T] means a list of T, not a T, so dont do that. [T] 表示 T 的列表,而不是 T,所以不要这样做。
If object_to_create is a function, do this.如果 object_to_create 是一个函数,请执行此操作。
# Use bound to limit the type to a specific ancestor.
T = TypeVar("T", bound="BaseCustomObject")
# Callable[..., T] is the type of a function
# that takes in whatever argument and returns an instance of T.
def my_func(
object_creator: Callable[..., T],
params: Optional[int] = 1
) -> T:
return object_creator(params) # Will return a T.
If object_to_create is a class
and not a function you instead use Type[T]
which will be the actual class and not a class instance.如果 object_to_create 是一个class
而不是一个函数,您可以使用Type[T]
,它是实际的类而不是类实例。
# Use bound to limit the type to a specific ancestor.
T = TypeVar("T", bound="BaseCustomObject")
def my_func(
object_to_create: Type[T],
params: Optional[int] = 1
) -> T:
return object_to_create(params) # Will return an instance of object_to_create.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.