用于解包对象的 Python 类型提示

标签 python mypy python-typing

我正在尝试为对象解包实现类型提示。这是我目前拥有的

from typing import Tuple


class A:
    def __init__(self, x: int, y: str):
        self.x = x
        self.y = y

    def astuple(self) -> Tuple[int, str]:
        return self.x, self.y

    # Need to annotate the return type of __iter__
    def __iter__(self):
        return iter(self.astuple())


a = A(1, "a")
# This cannot infer the type of x and y
x, y = a
reveal_type(x)
reveal_type(y)
# This infers the type of p and q as int and str respectively
p, q = a.astuple()
reveal_type(p)
reveal_type(q)

打印

$ mypy unpack_object.py
unpack_object.py:20: note: Revealed type is "Any"
unpack_object.py:21: note: Revealed type is "Any"
unpack_object.py:24: note: Revealed type is "builtins.int"
unpack_object.py:25: note: Revealed type is "builtins.str"
Success: no issues found in 1 source file

但是,我希望 mypy 能够推断出 xy (intstr) 的正确类型。我怎样才能实现这个目标?

最佳答案

无法在 Python 中定义自己的异构可迭代类型。使 A 成为 NamedTuple 的子类。

from typing import NamedTuple


class A(NamedTuple):
    x: int
    y: str


x, y = A(1, "a")
reveal_type(x)  # builtins.int
reveal_type(y)  # builtins.str

关于用于解包对象的 Python 类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75268412/

相关文章:

python - 在python中有一个列表,使用lambda和map/filter生成新列表

python - mypy vs mypy-lang vs pyls-mypy python包之间的区别

python - 指定 TypeVar 支持其值中的 "-"运算符

python - 使用 pymongo 在 MongoDB 中创建具有父子层次结构的数据库

python - 带有 TimeSeriesGenerator 的 Keras LSTM 自定义数据生成器

python - 在 Python 中,in 运算符是如何实现的?它是否使用迭代器的 next() 方法?

python - mypy:基类没有属性x,如何在基类中输入提示

python - 类型提示条件可变参数应用程序

python - Mypy:键入要加在一起的两个 int 或 str 列表

python - 来自 plt.subplots() 的 matplotlib 轴的精确类型注释数组 (numpy.ndarray)