为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

肥皂起泡泡 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条经验 获得超6个赞

如果您使用的是 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 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信