python / python/mypy

Mypy does not honor implicitly abstract class in stubs; false positive about ABCMeta

Open
#17,091 1 comment 2 reactions 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 analyzing stub files, mypy issues false positives when an implicitly abstract class inherits from abc.ABC rather than setting metaclass=ABCMeta:

To Reproduce

Have an implicitly abstract class in a file.

# bar.py
import abc
class A(abc.ABC):  # same behavior as if using metaclass=abc.ABCMeta here
    @abc.abstractmethod
    def meth(self) -> None:
        pass

class B(A):  # at runtime B.__class__ shows the metaclass is abc.ABCMeta
    pass

Import and subclass the implicitly abstract class

# foo.py
import bar

class C(bar.B):
    def meth(self) -> None:
        pass
$ mypy foo.py 
Success: no issues found in 1 source file

Rename the imported module so it's a stub.

$ mv bar.py bar.pyi

Expected Behavior

$ mypy foo.py 
Success: no issues found in 1 source file

Actual Behavior

$ mypy foo.py 
bar.pyi:10: error: Class bar.B has abstract attributes "meth"  [misc]
bar.pyi:10: note: If it is meant to be abstract, add 'abc.ABCMeta' as an explicit metaclass
Found 1 error in 1 file (checked 1 source file)

Mypy should emulate the runtime behavior and understand that B.__class__ is always going to be abc.ABCMeta.
Seems the bug is here: https://github.com/python/mypy/blob/master/mypy/semanal_classprop.py#L98-L100

Your Environment

  • Mypy version used: 1.9
  • Python version used: python 3.11

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 reproducing the issue with bar.py and foo.py, then rename bar.py to bar.pyi and run mypy foo.py. Inspect mypy/semanal_classprop.py around lines 98-100 to understand the stub handling. Done means the stub-based example reports no abstract-attribute error, matching the regular Python-module case.

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
Clearly specified
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.