python / python/mypy

No error when subclass does not provide a value for ClassVar

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

I've been trying to mypy to typecheck subclasses that need to provide a required value for a ClassVar in a base class that cannot provide the value itself (only has an unintialized attribute marker). The problem is that badly implemented subclasses can ignore this attribute without mypy raising errors about it (though interestingly if the value provided has incorrect type, mypy will raise errors about that).

To Reproduce

from abc import ABC
from typing import ClassVar, Type


class Base(ABC):
    my_super_important_value: ClassVar[str]


class GoodSubclass(Base):
    my_super_important_value = "1337"


# I want mypy to error about an unimplemented variable but it doesn't
class BadSubclass(Base):
    pass


def print_abc(cls: Type[Base]) -> None:
    print(cls.my_super_important_value)


print_abc(GoodSubclass)
# 1337
print_abc(BadSubclass)
# AttributeError: type object 'BadSubclass' has no attribute 'my_super_important_value'

mypy playground

Expected Behavior

Expected mypy to show an error about the BadSubclass class not providing a value for my_super_important_value.

Actual Behavior

No errors.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): N/A
  • Python version used: 3.10

Note that the same code fails when using the Pyre type checker with this error:

14:0: Uninitialized attribute [13]: Attribute `my_super_important_value` inherited from abstract class `Base` in class `BadSubclass` to have type `str` but is never initialized. 

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 Python reproducer from the issue with mypy --strict and confirm that BadSubclass produces no error while the runtime access fails. Investigate mypy's handling of inherited ClassVar declarations and abstract or uninitialized attributes, using the Pyre diagnostic as a behavioral comparison. Done means mypy reports that BadSubclass must provide my_super_important_value without breaking the GoodSubclass case.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers, devtools
Issue type
Bug
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.