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.
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
? I prefer not to use a Union type but to have the annotation/inspection/ide understand exactly which specific type I am getting back.
use a TypeVar generic type. [T] means a list of T, not a T, so dont do that.
If object_to_create is a function, do this.
# 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.
# 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.