python / python/mypy

False positive for Union[type, ...] and inspect.isclass()

Offen
#16,640 0 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-type-narrowing
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

When a variable's type is declared as a union that includes type (or typing.Type[...]), mypy does not take into account whether usage of that variable occurs inside of an if inspect.isclass(...) conditional block, leading to false positives.

To Reproduce

gist
playground

Python code
from inspect import isclass

registry: dict[str, type] = {}

def decorator_factory(arg: str | type):
    if isclass(arg):
        registry[arg.__name__.lower()] = arg
        return arg
    else:
        def decorator(cls: type):
            registry[arg] = cls
            return cls
        return decorator
        
@decorator_factory
class Foo:
    pass
        
@decorator_factory("alt")
class Bar:
    pass

Expected Behavior**

mypy reports no errors

Actual Behavior

main.py:11: error: Invalid index type "str | type" for "dict[str, type]"; expected type "str"  [index]
Found 1 error in 1 file (checked 1 source file)

Workaround

Using typing.cast to narrow the union explicitly.

gist
playground

Python code
from inspect import isclass
from typing import cast, TYPE_CHECKING

registry: dict[str, type] = {}

def decorator_factory(arg: str | type):
    if isclass(arg):
        registry[arg.__name__.lower()] = arg
        return arg
    else:
        if TYPE_CHECKING:
            arg = cast(str, arg)
        
        def decorator(cls: type):
            registry[arg] = cls
            return cls
        return decorator
        
@decorator_factory
class Foo:
    pass
        
@decorator_factory("alt")
class Bar:
    pass

Your Environment

  • Mypy version used: 1.7.1
  • Mypy command-line flags: (mypy-play defaults)
  • Mypy configuration options from mypy.ini (and other config files): (mypy-play defaults)
  • Python version used: 3.12

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

Führe zunächst den verlinkten Reproducer mit mypy aus und vergleiche den gemeldeten Fehler mit dem erwarteten Verhalten rund um inspect.isclass() und Union[type, ...]. Verfolge anschließend den Pfad der Typverengung für inspect.isclass und füge eine Regressionstestabdeckung für den Reproducer hinzu. Überprüfe, dass mypy ohne die cast-Umgehungslösung keine Fehler meldet.

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
38/100

Neue Issues direkt in Ihr Postfach

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