Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python type hints for unpacking object

I’m trying to implement type hinting for object unpacking. Here is what I have currently

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)

prints

$ 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

However, I would like mypy to infer correct types for x, y (int, str). How can I achieve this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

There is no way to define your own heterogeneous iterable type in Python. Make A a subclass of NamedTuple instead.

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading