Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change Type Hint of Inherited Method

Problem

Suppose you have a class A and a subclass B. If A has the method foo which returns a different variable type than B, how would you override the method's type hint without re-defining/overriding the method itself?

Realistic Example

class RGB:
    def __init__(self, color: Union[tuple[int, int, int], tuple[int, int, int, int]]) -> None:
        self.__color: Union[tuple[int, int, int], tuple[int, int, int, int]] = color
        return

    def __eq__(self, other: Union[RGB, RGBA]) -> bool:
        return isinstance(other, RGB) and self.__color == other.color

    @property
    def color(self) -> tuple[int, int, int]:
        return self.__color


class RGBA(RGB):
    def __init__(self, color: tuple[int, int, int, int]) -> None:
        super().__init__(color)
        return

    @property
    def color(self) -> tuple[int, int, int, int]:
        return self.__color

As you can see, the color attribute varies based on whether the given color has an alpha value or not. But I do not want/need to redefine/override the color property method, the functionality does not change. How would I define the return type hint for the color property without overriding the method?

Ideally, the RGBA class would just contain the __init__ function.

like image 771
VoidTwo Avatar asked Nov 21 '25 12:11

VoidTwo


1 Answers

You could have a generic Color class that serves as the common parent of both RGB and RGBA, parameterized by the tuple type used to represent each. For example,

from typing import Generic, TypeVar


C = TypeVar('C')


class Color(Generic[C]):
    def __init__(self, c: C):
        self.__color = c

    @property
    def color(self) -> C:
        return self.__color


class RGB(Color[tuple[int,int,int]]):
    pass


class RGBA(Color[tuple[int,int,int,int]]):
    pass

This is just a start; you may run into other problems as you add more details to the classes.

like image 99
chepner Avatar answered Nov 23 '25 00:11

chepner