Python typing: mypy complains about bound TypeVar having incompatible type with subclass of that type

Viewed 304

The following code results in the error 28: error: List item 0 has incompatible type "ExampleRule[<nothing>]"; expected "RuleSub" [list-item]. How can I change the type annotations to be correct?

from typing import *

EdgeSub = TypeVar('EdgeSub', bound='EdgeBase')
RuleSub = TypeVar('RuleSub', bound='RuleBase')


class EdgeBase:
    pass


class RuleBase(Generic[EdgeSub]):
    def proposeEdges(self) -> list[EdgeSub]:
        return []

    def allowEdge(self, edge: EdgeSub) -> bool:
        return True


class ExampleRule(RuleBase[EdgeSub]):
    def proposeEdges(self) -> list[EdgeSub]:
        return []

    def allowEdge(self, edge: EdgeSub) -> bool:
        return True


def get_rule_list() -> list[RuleSub]:
    weapon_rule_list: list[RuleSub] = [ExampleRule()]  # This is line 28 with the error
    return weapon_rule_list

Note that in the non-simplified implementation, ExampleRule.proposeEdges returns a list of instances of many different subclasses of EdgeBase, hence needing the EdgeSub type var. Similarly, get_rule_list needs to return many different types of rules.

0 Answers
Related