我有這個: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
添加回答
舉報
0/150
提交
取消