簡體   English   中英

如何根據輸入參數值提示函數返回?

[英]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_listfactory值為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) -> listbuild_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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM