[英]How to type-hint a function return based on input parameter value?
How can I type-hint a function in Python based on the value of an input parameter?如何根据输入参数的值对 Python 中的函数进行类型提示?
For instance, consider the following snippet:例如,请考虑以下代码段:
from typing import Iterable
def build(
source: Iterable,
factory: type
) -> ?: # what can I write here?
return factory(source)
as_list = build('hello', list) # -> list ['h', 'e', 'l', 'l', 'o']
as_set = build('hello', set) # -> set {'h', 'e', 'l', 'o'}
When building as_list
, the value of factory
is list
, and this should be the type annotation.构建
as_list
, factory
值为list
,这应该是类型注解。
I am aware of this other question , but, in that case, the return type depended only on the input types , not on their values .我知道另一个问题,但是,在那种情况下,返回类型仅取决于输入类型,而不取决于它们的值。 I would like to have
def build(source: Iterable, factory: type) -> factory
, but of course this doesn't work.我想要
def build(source: Iterable, factory: type) -> factory
,但这当然行不通。
I am also aware of Literal types in Python 3.8+, and something similar to this could be achieved:我也知道 Python 3.8+ 中的Literal 类型,并且可以实现类似的东西:
from typing import Iterable, Literal, overload
from enum import Enum
FactoryEnum = Enum('FactoryEnum', 'LIST SET')
@overload
def build(source: Iterable, factory: Literal[FactoryEnum.LIST]) -> list: ...
@overload
def build(source: Iterable, factory: Literal[FactoryEnum.SET]) -> set: ...
But this solution would make factory
useless (I could just define two functions build_list(source) -> list
and build_set(source) -> set
).但是这个解决方案会使
factory
无用(我可以只定义两个函数build_list(source) -> list
和build_set(source) -> set
)。
How can this be done?如何才能做到这一点?
Rather than using type
, you could use a generic and define the factory
as a Callable
, as follows:您可以使用泛型并将
factory
定义为Callable
,而不是使用type
,如下所示:
from typing import Callable, Iterable, TypeVar
T = TypeVar('T')
def build(
source: Iterable,
factory: Callable[[Iterable], T]
) -> T:
return factory(source)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.