如何根據輸入參數的值對 Python 中的函數進行類型提示?例如,考慮以下代碼片段:from typing import Iterabledef 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, overloadfrom enum import EnumFactoryEnum = Enum('FactoryEnum', 'LIST SET')@overloaddef build(source: Iterable, factory: Literal[FactoryEnum.LIST]) -> list: ...@overloaddef build(source: Iterable, factory: Literal[FactoryEnum.SET]) -> set: ...但這個解決方案毫無用處factory(我可以只定義兩個函數build_list(source) -> list和build_set(source) -> set)。如何才能做到這一點?
1 回答

一只名叫tom的貓
TA貢獻1906條經驗 獲得超3個贊
type
您可以使用泛型并將 定義factory
為 a ,而不是使用Callable
,如下所示:
from typing import Callable, Iterable, TypeVar
T = TypeVar('T')
def build(
? ? source: Iterable,
? ? factory: Callable[[Iterable], T]
) -> T:
? ? return factory(source)
添加回答
舉報
0/150
提交
取消