[英]How to type-hint a function return based on input parameter value?
如何根据输入参数的值对 Python 中的函数进行类型提示?
例如,请考虑以下代码段:
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'}
构建as_list
, factory
值为list
,这应该是类型注解。
我知道另一个问题,但是,在那种情况下,返回类型仅取决于输入类型,而不取决于它们的值。 我想要def build(source: Iterable, factory: type) -> factory
,但这当然行不通。
我也知道 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: ...
但是这个解决方案会使factory
无用(我可以只定义两个函数build_list(source) -> list
和build_set(source) -> set
)。
如何才能做到这一点?
您可以使用泛型并将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.