Return instance of bounded typevar given an *args parameter with type of typevar parameter

26 views Asked by At

So I have this code:

from __future__ import annotations

from typing import TypeVar, overload


class Base:
    base_var: int


class ComponentOne(Base):
    component_one_var: float


class ComponentTwo(Base):
    component_two_var: str


T = TypeVar("T", bound=Base)
T1 = TypeVar("T1", bound=Base)
T2 = TypeVar("T2", bound=Base)


class Registry:
    def __init__(self) -> None:
        self._registry: dict[int, dict[type[Base], Base]] = {
            1: {ComponentOne: ComponentOne(), ComponentTwo: ComponentTwo()},
            2: {ComponentOne: ComponentOne()},
            3: {ComponentTwo: ComponentTwo()},
            4: {},
            5: {ComponentOne: ComponentTwo(), ComponentTwo: ComponentOne()},
        }

    @overload
    def get(self, __component_one: type[T]) -> list[tuple[int, T]]:
        ...

    @overload
    def get(
        self, __component_one: type[T], __component_two: type[T1]
    ) -> list[tuple[int, tuple[T, T1]]]:
        ...

    @overload
    def get(
        self,
        __component_one: type[T],
        __component_two: type[T1],
        __component_three: type[T2],
    ) -> list[tuple[int, tuple[T, T1, T2]]]:
        ...

    def get(self, *components: type[Base]) -> list[tuple[int, tuple[Base, ...]]]:
        return []


f = Registry()
for game_object_id, component_one in f.get(ComponentOne):
    print(game_object_id, component_one)

This program is a simplified version of an entity component system which holds game object IDs and their components. However, when running mypy on it, I get the error:

t.py:52:5:53:17: error: Overloaded function implementation cannot produce return type of signature 1  [misc]
        def get(self, *components: type[Base]) -> list[tuple[int, tuple[Base, ...]]]:
        ^
t.py:52:5:53:17: error: Overloaded function implementation cannot produce return type of signature 2  [misc]
        def get(self, *components: type[Base]) -> list[tuple[int, tuple[Base, ...]]]:
        ^
t.py:52:5:53:17: error: Overloaded function implementation cannot produce return type of signature 3  [misc]
        def get(self, *components: type[Base]) -> list[tuple[int, tuple[Base, ...]]]:

How can I fix this typing error so each signature matches the implemented method?

0

There are 0 answers