python / python/mypy

Base class type incorrectly overwritten by assignment in extending class

Open
#17,255 1 comment 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

Defining a variable with a type union or optional, etc. and then setting the variable in an extending class overwrites the type of the variable to the narrower type used in the assignment. E.g. int | str to int. If the class is extended again, the type of the variable is the narrower type and can't be broadened again by a simple assignment or changed to another type compatible with the original base class.

To Reproduce

The following code results in an incompatible types in assignment error in the Eggs class:

class Spam:
    var: int | str

class Ham(Spam):
    var = 10

class Eggs(Ham):
    var = "abc"

Expected Behavior

I would expect the explicitly set type of the base class Spam to be inherited by the first extending class Ham and that an assignment doesn't change the general type of the variable. So that the second extending class can still set var to a str.

Just like the following code is valid:

var: str | int
var = 10
var = "abc"

Actual Behavior

The assignment in Ham sets the type of var to int and the class Eggs can't set var to "abc" of type str.

mypy output:
a.py:8: error: Incompatible types in assignment (expression has type "str", base class "Ham" defined the type as "int") [assignment]

Your Environment

  • Mypy version used: mypy 1.10.0 (compiled: yes)
  • Python version used: Python 3.12.3 (main, Apr 23 2024, 09:16:07) [GCC 13.2.1 20240417] on linux

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

Reproduce the three-class snippet with mypy 1.10.0 and inspect how the explicitly annotated union in Spam is handled across assignments in Ham and Eggs. Done means Ham's assignment does not narrow the inherited type, and Eggs accepts the string assignment without an incompatible-types error.

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
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.