python / python/mypy

Type detection broken on attribute override and not-equal-assertion

Offen
#11,226 2 Kommentare 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

I commonly find myself writing simplified list init parameters. So, if the user provides only a type X, I automatically convert that to list type [X]. In doing so, I found two issue that prevent a proper type detection. See the example code below.

To Reproduce

#!/usr/bin/env python3
from typing import Union, List, Optional

def test(a: Union[List[str], str, None] = None) -> Optional[List[str]]:
    if type(a) == str:
        a = [a]
    assert(type(a) != str)
    return a

Expected Behavior

  1. First, the type(a) == str check and consequent list assignment should remove the str type from the Union choices.
  2. Second, the assert(!=) check should also remove the str type from the Union options.

Actual Behavior

Both checks do not work and the type is still guessed incorrectly:

screen

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: pip install
  • Mypy configuration options from mypy.ini (and other config files): -
  • Python version used: 3.8
  • Operating system and version: macOS 10.15

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, den bereitgestellten Python-Reproducer mit mypy auszuführen, und untersuche das Verhalten der Typverengung für die Zuweisung type(a) == str und die Prüfung assert(type(a) != str). Als erledigt gilt die Aufgabe, wenn beide Zweige str aus der inferierten Union entfernen und die Funktion mit dem erwarteten Rückgabetyp Optional[List[str]] akzeptiert wird.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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