python / python/mypy

confusing behavior with TypeVars and multiple inheritance checks in 0.770

Offen
#8,604 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

topic-inheritance topic-type-variables
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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!

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

Beginne damit, mypy 0.770 oder das TypeVar- und Mehrfachvererbungsbeispiel des Issues auszuführen, um die aufgedeckten Typen und den Zuweisungsfehler zu reproduzieren. Lies anschließend die relevante Dokumentation zu TypeVar und Typeneingrenzung sowie die Diagnosetests und dokumentiere dann das Verhalten, einen Workaround und eine klarere Formulierung für die Beziehung zwischen Foo und dem abgeleiteten Subklassentyp.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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