python / python/mypy

Base class type incorrectly overwritten by assignment in extending class

Offen
#17,255 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Reproduziere das Drei-Klassen-Snippet mit mypy 1.10.0 und untersuche, wie die explizit annotierte Union in Spam bei Zuweisungen in Ham und Eggs behandelt wird. Erledigt ist dies, wenn Hams Zuweisung den geerbten Typ nicht verengt und Eggs die Zuweisung eines Strings ohne einen incompatible-types-Fehler akzeptiert.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
tooling
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.