python / python/mypy

Concrete class considered abstract when base class has additional python type

Open
#14,067 0 comments 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

Bug Report

When using a TypeVar from an abstract class, and the abstract class additionally inherits from some integrated types (I found dict, int, str, set; not float), mypy incorrectly alarms about instantiating an abstract class.

To Reproduce

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


class User(ABC, dict):  # removing dict makes mypy happy
    @abstractmethod
    def method(self):
        ...


class BasicUser(User):
    def method(self):
        print('basic')


U = TypeVar('U', bound=User)


def new_user(user_class: Type[U]) -> U:
  user = user_class()
  return user


joe = new_user(BasicUser)

Expected Behavior

It should not report an error, as it does not when inheriting from another class or just ABC.

Actual Behavior

test.py:20: error: Cannot instantiate abstract class "User" with abstract attribute "method" [abstract]

Your Environment

  • Mypy version used: 0.990
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10.8

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 by running the supplied test.py reproduction with mypy 0.990 and confirm the abstract-class error for BasicUser. Trace the handling of TypeVar bounds, abstract methods, and additional built-in base classes, then add a regression test showing that new_user(BasicUser) is accepted without the false diagnostic.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.