python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.46k stars 2.83k forks source link

Inheriting from untyped class and overriding `__init__` breaks abstract class detection #17781

Open Kakadus opened 1 month ago

Kakadus commented 1 month ago

Bug Report

I'm creating an ABC inheriting from an untyped class and override its __init__ function. Then, all child classes are detected as being abstract, even though they are not.

The error is not caused when removing the overriding the init function or removing the inheritance from the untyped base class

To Reproduce

from abc import ABC, abstractmethod

from untyped import Base  # type: ignore[import-not-found]

class Abstract(ABC, Base):

    def __init__(self):
       super().__init__()

    @abstractmethod
    def method(self) -> None: ...

class Concrete(Abstract):

    def method(self) -> None: ...

C: type[Abstract] = Concrete  # E: Can only assign concrete classes to a variable of type "type[Abstract]"  [type-abstract]

https://mypy-play.net/?mypy=1.11.2&python=3.12&gist=6b11b5a5c3ef54947fb0874cade6ce98

Expected Behavior

This code should not produce any errors as the abstract method is implemented.

Actual Behavior

Your Environment

Kakadus commented 1 month ago

Making Abstract generic, this leads to this funny error: Expression is of type "dict[str, type[Abstract[Any]]]", not "dict[str, type[Abstract[Any]]]":

from abc import ABC, abstractmethod

from typing import assert_type, TypeVar, Generic

from untyped import Base  # type: ignore[import-not-found]

T = TypeVar("T")

class Abstract(ABC, Base, Generic[T]):

    def __init__(self):
       super().__init__()

    @abstractmethod
    def method(self) -> None: ...

class ConcreteA(Abstract[str]):

    def method(self) -> None: ...

class ConcreteB(Abstract[int]):

    def method(self) -> None: ...

a = {"a": ConcreteA, "b": ConcreteB}

assert_type(a, dict[str, type[Abstract]])  # Expression is of type "dict[str, type[Abstract[Any]]]", not "dict[str, type[Abstract[Any]]]"  [assert-type]

https://mypy-play.net/?mypy=1.11.2&python=3.12&gist=4f015c7663819c49d6f1d86f751f9187