Skip to content

Only concrete class can be given where "Type[Abstract]" is expected when creating a list comprehension of an ABC's concrete subclasses #16442

Closed as not planned
@cwilson-mdmi

Description

@cwilson-mdmi

I'm getting an error when creating a list of classes using a comprehension. The classes are concrete subclasses of an abstract base class.

from abc import ABC, abstractmethod
from typing import Type

class Abstract(ABC):
    @abstractmethod
    def method(self):
        ...

class Concrete1(Abstract):
    def method(self):
        pass

class Concrete2(Abstract):
    def method(self):
        pass

literal_registry: list[Type[Abstract]] = [Concrete1, Concrete2]  # no error

generated_registry: list[Type[Abstract]] = [
    cls for cls in (Concrete1, Concrete2)  # error: Only concrete class can be given where "Type[Abstract]" is expected  [type-abstract]
]

This error disappears if I remove the @abstractmethod decorator.

There is also no error if I only iterate over a tuple with only one element, like so:

generated_registry: list[Type[Abstract]] = [cls for cls in (Concrete1,)]  # no error

 

  • Mypy version used: 1.3.0
  • Python version used: 3.10.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-join-v-unionUsing join vs. using unions

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions