python / python/mypy

Base class type incorrectly overwritten by assignment in extending class

Aperta
#17,255 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproduci lo snippet a tre classi con mypy 1.10.0 e verifica come viene gestita l’union annotata esplicitamente in Spam nelle assegnazioni in Ham ed Eggs. Il lavoro è completato quando l’assegnazione di Ham non restringe il tipo ereditato ed Eggs accetta l’assegnazione della stringa senza un errore incompatible-types.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.