打字:函数返回带有解包列表的元组时的类型提示

我有这个:


from typing import Tuple

import random


a = random.randint(100) # some random number


def 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 Tuple

import random


a = random.randint(100) # some random number. It doesn't matter


def 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, *b

Pycharm 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, ...]]: ...


肥皂起泡泡
浏览 83回答 1
1回答

LEATH

如果您使用的是 Python 3.11或更高版本,则可以简单地在返回类型的类型提示中使用解包星号 ( *),类似于您在问题中的写法(但略有不同,请参见下面的示例)。但是,截至撰写本文时,Python 3.11 仍未公开,您可能使用的是3.10 或更早版本。如果是这种情况,您可以使用向后移植的特殊类型Unpack,它typing_extensions在pypi上可用。用法示例:from typing_extensions import Unpack# Python <=3.10def unpack_hints_py_10_and_below(args: list[str]) -> tuple[int, Unpack[str]]:    first_arg, *rest = args    return len(first_arg), *rest# Python >= 3.11def unpack_hints_py_11_and_above(args: list[str]) -> tuple[int, *str]:    first_arg, *rest = args    return len(first_arg), *rest
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python