繁体   English   中英

打字:当 function 返回带有解压列表的元组时,键入提示

[英]typing: type hinting when function returns tuple with unpacked list

我有这个:

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

我想为此 function 编写返回类型,但我现在不知道如何正确执行此操作:

我试过这个:

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]但我需要 function 来返回传递给它的变量类型

在一个真实的项目中,它接受一个泛型并返回一个包含 object 的元组和其中的解压列表以提高可读性

真正的 function:

...
    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

打字愉快!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM