如何根据输入参数值类型提示函数返回?

如何根据输入参数的值对 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值为,这应该是类型注释。factorylist

在这种情况下,返回类型仅取决于输入类型,而不取决于它们的。我想要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: ...

但这个解决方案毫无用处factory(我可以只定义两个函数build_list(source) -> list和build_set(source) -> set)。


如何才能做到这一点?


aluckdog
浏览 72回答 1
1回答

一只名叫tom的猫

type您可以使用泛型并将 定义factory为 a ,而不是使用Callable,如下所示:from typing import Callable, Iterable, TypeVarT = TypeVar('T')def build(    source: Iterable,    factory: Callable[[Iterable], T]) -> T:    return factory(source)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python