Python 如何根据输入参数值键入函数返回提示?
如何根据输入参数的值在Python中键入提示函数Python 如何根据输入参数值键入函数返回提示?,python,python-3.x,type-hinting,Python,Python 3.x,Type Hinting,如何根据输入参数的值在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']
例如,考虑下面的片段:
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'}
在将构建为列表
时,工厂
的值为列表
,这应该是类型注释
我知道,但是,在这种情况下,返回类型只依赖于输入类型,而不依赖于它们的值。
我希望有def build(source:Iterable,factory:type)->factory
,但这当然不行
我还了解Python 3.8+中的一些功能,可以实现类似的功能:
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: ...
但是这个解决方案会使工厂变得无用(我可以定义两个函数build\u list(source)->list
和build\u set(source)->set
)
如何做到这一点?您可以使用,而不是使用
类型,并将工厂定义为可调用的,如下所示:
from typing import Callable, Iterable, TypeVar
T = TypeVar('T')
def build(
source: Iterable,
factory: Callable[[Iterable], T]
) -> T:
return factory(source)
为什么工厂不是类型
,例如可调用[[Iterable],t]
?然后返回值是T
(参见示例)。@jornsharpe这实际上是个好主意,我不知道我怎么会错过它。你介意为这个问题写一个答案吗?太好了,谢谢!这个答案强调了一个事实,即类本身是可调用的。