亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

打字:函數返回帶有解包列表的元組時的類型提示

打字:函數返回帶有解包列表的元組時的類型提示

肥皂起泡泡 2023-05-23 16:00:30
我有這個:from typing import Tupleimport randoma = random.randint(100) # some random numberdef foo(a: int) -> Tuple:    b = []    for _ in random.randint(0, 10):       b.append(random.randint(-5, 5) # adding random numbers to b    return a, *b我想為這個函數寫返回類型,但我現在不知道如何正確地做到這一點:我試過這個:from typing import Tupleimport randoma = random.randint(100) # some random number. It doesn't matterdef foo(a: int) -> Tuple[int, *Tuple[int, ...]]:    b = []    for _ in random.randint(0, 10):       b.append(random.randint(-5, 5) # adding random numbers to b    return a, *bPycharm with mypy說:foo(a: int) -> Tuple[int, Any] 但我需要函數返回傳遞給它的變量類型在實際項目中,它采用泛型并返回一個元組,其中包含對象和解包列表以提高可讀性。實函數:...    def get_entities_with(self, *component_types):        for entity in self.entities.values():            require_components = [component for component in entity.components if type(component) in component_types]            if len(require_components) == len(component_types):                yield entity, *require_components....py 文件:T = TypeVar("T")...    def get_entities_with(self, *components:Type[T]) -> Generator[Entity, *Tuple[T, ...]]: ...
查看完整描述

1 回答

?
LEATH

TA貢獻1936條經驗 獲得超7個贊

如果您使用的是 Python?3.11或更高版本,則可以簡單地在返回類型的類型提示中使用解包星號 (?*),類似于您在問題中的寫法(但略有不同,請參見下面的示例)。

但是,截至撰寫本文時,Python 3.11 仍未公開,您可能使用的是3.10 或更早版本。如果是這種情況,您可以使用向后移植的特殊類型Unpack,它typing_extensions在pypi上可用。

用法示例:

from typing_extensions import Unpack


# Python <=3.10

def unpack_hints_py_10_and_below(args: list[str]) -> tuple[int, Unpack[str]]:

? ? first_arg, *rest = args

? ? return len(first_arg), *rest


# Python >= 3.11

def unpack_hints_py_11_and_above(args: list[str]) -> tuple[int, *str]:

? ? first_arg, *rest = args

? ? return len(first_arg), *rest

查看完整回答
反對 回復 2023-05-23
  • 1 回答
  • 0 關注
  • 146 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號