我有这个:
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 和 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
...
.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/