python - 输入 : type hinting when function returns tuple with unpacked list

标签 python python-3.x iterable-unpacking python-typing

我有这个:

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

Pycharmmypy 说: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
...

.pyi 文件:

T = TypeVar("T")
...
    def get_entities_with(self, *components:Type[T]) -> Generator[Entity, *Tuple[T, ...]]: ...

最佳答案

如果您使用的是 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

进一步(重度)阅读: 参见 PEP 646 .

打字愉快!

关于python - 输入 : type hinting when function returns tuple with unpacked list,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63401681/

相关文章:

python - 从 Pandas 中的滚动窗口生成值组合

python - 在 python3 中清除异步队列的正确方法?

python - 为什么 zip 急切地评估其参数的元素?

python - Pandas :连接文件但跳过第一个文件以外的标题

python - 对对象方法使用 Python 模拟的 autospec 的正确方法是什么?

Python itertools : Best way to unpack product of product of list of lists

python - 有多个值需要解压

python - isinstance(object, type) 给了我一个错误 - 另外,展平嵌套列表

Python - 在窗口最小化或隐藏时使用 pywinauto 控制窗口

python - 名称错误 : name 'app' is not defined with Flask