python / python/mypy

False positive comparison-overlap for nested function and nested class

Offen
#15,083 0 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

Nested functions inside methods incorrectly resolve attributes of their first argument relative to the surrounding class.

To Reproduce

class foo:
    a: str = "foo"
    
class bar:
    class a:
        pass
    
    def test(self) -> None:
        def inner1(f: foo, s: str) -> bool:
            return f.a == s
        
        def inner2(s: str, f: foo) -> bool:
            return f.a == s

https://mypy-play.net/?mypy=latest&python=3.11&flags=strict&gist=4c27f653074cd1c3a48bb16f49ca2168

Expected Behavior

As far as I can tell this should be valid code, even though this rarely happens in practice due to CamelCase vs snake_case naming conventions.

Actual Behavior

inner1 fails to type-check, because the a attribute is incorrectly assumed to be the a class inside bar

main.py:10: error: Non-overlapping equality check (left operand type: "Type[a]", right operand type: "str")  [comparison-overlap]

Interestingly, inner2 is fine.

Your Environment

  • Mypy version used: 1.2.0
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11

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

Reproduziere das Beispiel aus dem Issue in mypy mit Python 3.11 und --strict und verfolge anschließend, wie die verschachtelten Funktionen den Attributzugriff im Vergleich auflösen. Die Korrektur ist abgeschlossen, wenn inner1 keinen Fehler comparison-overlap mehr meldet, während inner2 weiterhin gültig bleibt und die Regression durch einen Test abgedeckt ist.

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.