python / python/mypy

confusing behavior with TypeVars and multiple inheritance checks in 0.770

Aperta
#8,604 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

topic-inheritance topic-type-variables
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Hi, I was just testing out 0.770 and I'm getting a surprising result:

from typing import TypeVar

class Foo(object):
    pass

FooOrStr = TypeVar('FooOrStr', Foo, str)

def doit(reset: bool, arg: FooOrStr) -> FooOrStr:
    if reset:
        if isinstance(arg, Foo):
            reveal_type(arg)
            arg = Foo()
        elif isinstance(arg, str):
            reveal_type(arg)
            arg = ''
        else:
            raise TypeError()
    return arg
test.py:12: note: Revealed type is 'test.Foo*'
test.py:12: note: Revealed type is 'test.<subclass of "str" and "Foo">'
test.py:13: error: Incompatible types in assignment (expression has type "Foo", variable has type "str")  [assignment]
test.py:15: note: Revealed type is 'builtins.str*'

Based on the latest blog post about 0.770 I suspect this is by design, but what can I do to work around it (short of adding some artificial method to make Foo incompatible with str)?

It would be good to add something to the docs about this, because I think it could be a fairly common trap. Also, I think adjusting the error message to clarify the relationship to multiple inheritance would help, e.g. variable has type Foo and 'test.<subclass of "str" and "Foo">'.

Thanks!

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 mypy 0.770 o l'esempio di TypeVar e di ereditarietà multipla dell'issue per riprodurre i tipi rivelati e l'errore di assegnazione. Leggi la documentazione pertinente su TypeVar e sul restringimento dei tipi e i test diagnostici, quindi documenta il comportamento, una soluzione alternativa e una formulazione più chiara della relazione tra Foo e il tipo di sottoclasse inferito.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.