Skip to content

Non generic subclass of generic class do not resolve type correctly #5831

@dswistowski

Description

@dswistowski

I have code

from abc import ABC, abstractmethod
from typing import TypeVar, Generic, Dict, Type

T = TypeVar('T')


class GenericClass(Generic[T], ABC):
    children: Dict[str, Type[T]]

    @classmethod
    def by_name(cls, name: str) -> T:
        return cls.children[name]()

    def __init_subclass__(cls):
        super().__init_subclass__()
        try:
            cls.children[cls.__name__.lower()] = cls
        except AttributeError:
            cls.children = {}


class NonGenericBase(GenericClass['NonGenericBase'], ABC):
    @abstractmethod
    def my_method(self) -> bool:
        pass


class Child(NonGenericBase):
    def my_method(self) -> bool:
        return True


NonGenericBase.by_name('child').my_method()

Checking that code with mypy generates:
test.py:33: error: "T" has no attribute "my_method"

From my understanding type of NonGenericBase.by_name should be Callable[[str], NonGenericBase] (because NonGenericBase is GenericClass['NonGenericBase']) but it looks like it is Callable[[str], T]

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions