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

qlvxas9a  于 2023-01-29  发布在  Python
关注(0)|答案(1)|浏览(152)

我正在尝试为对象解包实现类型提示。

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能够推断出xyintstr)的正确类型,我该如何实现呢?

dzjeubhm

dzjeubhm1#

在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

相关问题