python / python/mypy

Args with a generic type will use the mother type, rather than a literal

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

Nessuno ha ancora preso questa issue.

bug topic-join-v-union
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report
Args with a generic type will use the mother type, rather than a literal

I noticed this issue while trying to chain together two lists with different types with itertools.chain.

To Reproduce

from typing import TypeVar

T = TypeVar('T')

class M:
    pass


class C1(M):
    def my_method(self) -> None:
        pass

class C2(M):
    def my_method(self) -> None:
        pass


def test(*args: T) -> T:
    return args[0]

result = test(C1(), C2())
result.my_method()

https://mypy-play.net/?mypy=latest&python=3.12&flags=strict&gist=d78c6875b87a3040126e1926b8f7ba0c

Expected Behavior
I expected to be able to run my_method, as all arguments have it defined. Instead the mother type is used. This issue can be mitigated by extracting the arguments, giving them a literal type, then unpack them into the function:

my_args: list[C1 | C2] = [C1(), C2()]
test(*my_args)

Actual Behavior

main.py:26: error: "M" has no attribute "my_method"  [attr-defined]

I believe this happens because untyped lists defined with items will use the mother type of all items. I don't think this is very intuitive for args.

Visual Studio Code's Pylance does not give an error in this situation, even with the strict flag.

Your Environment

  • Mypy version used: 1.9.0
  • Mypy command-line flags: no flags
  • Mypy configuration options from mypy.ini (and other config files): no config
  • Python version used: 3.9, 3.10, 3.11, 3.12

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

Inizia eseguendo la riproduzione mypy-play fornita con le versioni indicate di Python e mypy, quindi traccia l’inferenza degli argomenti generici per l’esempio test(*args: T) -> T. Il lavoro è completato quando la chiamata che combina C1 e C2 viene inferita come un tipo che espone my_method senza richiedere la lista annotata intermedia, con una copertura di regressione per questo comportamento.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.