如何基于输入参数的 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
,这应该是类型注释。
我知道this other question,但是在那种情况下,返回类型仅取决于输入的类型,而不取决于其值。
我想拥有def build(source: Iterable, factory: type) -> factory
,但是这当然行不通。
我也知道Python 3.8+中的Literal types,并且可以实现类似的目的:
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
)。
这怎么办?
答案 0 :(得分:2)
您可以使用generic并将type
定义为factory
,而不是使用Callable
,如下所示:
from typing import Callable, Iterable, TypeVar
T = TypeVar('T')
def build(
source: Iterable,
factory: Callable[[Iterable], T]
) -> T:
return factory(source)