python / python/mypy

enumerating concrete subclasses of an abstract base class causes false positive "Cannot instantiate abstract class X with abstract attribute Y"

Open
#16,274 1 comment 1 reaction 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

I have a number of concrete classes which all derive from the same abstract base class. Creating a list of instances using __subclasses__() in a list comprehension, mypy complains that I'm trying to instantiate the abstract class.

Simple example:
https://mypy-play.net/?mypy=latest&python=3.11&gist=f03c51fac1173ae0bb751b00e614de68

from abc import ABC, abstractmethod
from typing import List

class Animal(ABC):
    @abstractmethod
    def talk(self) -> str:
        pass

class Dog(Animal):
    def talk(self) -> str:
        return "woof"

class Cat(Animal):
    def talk(self) -> str:
        return "miaow"

# enumerate using __subclasses__()
animals: List[Animal] = [
    subclass() for subclass in Animal.__subclasses__()
]
print(animals)

# hard-coding subclass instances is fine
animals2: List[Animal] = [
     Dog(), Cat()
]

Expected Behavior
As I'm not actually instantiating the abstract class, the mypy error looks like a false positive.

Your Environment
python 3.10.12
mypy v1.6.0

Possibly related issues
#15554
#14106
#3115

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the mypy-play example in the issue and reproduce the diagnostic for the subclasses() list comprehension. Read the related issues #15554, #14106, and #3115 for existing context. Done means the example no longer reports an abstract-class instantiation error while genuine abstract-class instantiations remain diagnosed.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.