Search code examples
python-3.xpycharmtuples

In Python 3, how to properly subclass a tuple to create a pair, with proper type hints?


Suppose that I would need to subclass the tuple to create a pair of two float numbers. Besides normal tuple functionality, I would like to have properties .x and .y to access the two values.

I often use PyCharm to do some larger projects, so type hinting is quite essential for me. So I am adding typing information for better maintenance in long term.

Some sample code below:

from typing import Tuple

class Pair(Tuple[float, float]):
    def __new__(cls, x: float, y: float):
        pair = super().__new__(cls, (x, y))
        return pair

    @property
    def x(self):
        return self[0]

    @property
    def y(self):
        return self[1]

    def __str__(self):
        return f'({self.x},{self.y})'


if __name__ == '__main__':
    a = Pair(1, 2)
    print(a)
    print(a.x)
    print(a.y)

Outputs:

(1,2)
1
2

But PyCharm keeps warning that

Expected type 'Type[_T]', got 'Pair' instead.

Is there something wrong with the __new__ function?


Solution

  • Consider using a NamedTuple. It suits your case well and is supported by PyCharms type analyser.