python / python/mypy

Subclass default overrides more general baseclass type hint

Open
#11,897 1 comment 2 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Bug Report

When a base class field has a general type hint (eg: Union[int, str] or a base class) and a subclass sets a default without a type hint, the field's type hint is narrowed to the specific default value's type rather than maintaining the original base class's hint. This prevents a second-order subclass from setting a new default with a different type that would otherwise align with the originally specified hint on the first class.

This is particularly relevant when using something like dataclasses or pydantic.

To Reproduce

from typing import Union

class A:
    x: Union[int, str] = 5

class B(A):
    x = 5

class C(B):
    # error: Incompatible types in assignment (expression has type "str", base class "B" defined the type as "int")
    x = "5"

class RefA:
    x: A

class RefB(RefA):
    x = B()

class RefC(RefB):
    # error: Incompatible types in assignment (expression has type "A", base class "RefB" defined the type as "B")
    x = A()

Expected Behavior

The B.x and RefB.x fields to maintain their base classes type hint rather than implicitly narrow to the default value's type. Thus, C.x and RefC.x fields to support values matching the first base class's type hint.

Actual Behavior

The middle subclasses implicitly narrow the type hint to type(default_value) so a new default on a third subclass must match that, rather than the original explicit hint.

Your Environment

  • Mypy version used: 0.930
  • Mypy command-line flags: n/a
  • Mypy configuration options from mypy.ini (and other config files): n/a
  • Python version used: 3.9.7
  • Operating system and version: macos 12.0.1

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 supplied A/B/C and RefA/RefB/RefC inheritance examples and trace how mypy infers unannotated subclass assignments. Add regression coverage showing that B.x and RefB.x retain the original base annotations, and verify that the third-level assignments no longer produce the reported incompatibility errors.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 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.