python / python/mypy

Mypy not inferring return type of dict.get()

Offen
#20,631 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

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

Beschreibung

Bug Report

Mypy fails to infer the return type of dict.get(), even though the dictionary is fully type-hinted, triggering a no-any-return error when Mypy is run in --strict mode.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.14&flags=strict&gist=61ec65a894e2259d4b3a0e65ef31c33c

from typing import ClassVar, Final, Self, Any


class Interface:

    # Every subclass has a _name attribute (set by __init_subclass__)
    _name: ClassVar[Final[str]]

    # Registry of subclasses
    _iftypes: ClassVar[Final[dict[str, type[Self]]]] = {}

    def __init_subclass__(cls, **kwargs: Any) -> None:
        super().__init_subclass__(**kwargs)
        name = cls.__name__.lower()
        cls._name = name
        cls._iftypes[name] = cls

    def __init__(self, ifname: str) -> None:
        self._ifname = ifname

    @classmethod
    def from_registry(cls, name: str, kind: str) -> Self:
        #ifcls: type[Self] | None = cls._iftypes.get(kind)
        ifcls = cls._iftypes.get(kind)
        if ifcls is None:
            raise ValueError()
        return ifcls(name)


class Bond(Interface):
    pass


class Bridge(Interface):
    pass


class VLAN(Interface):
    pass


for kind, ifcls in Interface._iftypes.items():
    print(f'{kind}: {ifcls.__name__}')

Expected Behavior

Mypy should infer that the object returned by dict.get() and assigned to ifcls on line 25 is type[Self] | None, which is narrowed to just type[Self] by the check on line 26. Thus, calling its constructor must return a instance of Self.

Actual Behavior

$ mypy --strict bug.py
main.py:28: error: Returning Any from function declared to return "Self"  [no-any-return]
Found 1 error in 1 file (checked 1 source file)

Your Environment

Fedora 43 (x86_64)
python3-3.14.2-1.fc43.x86_64
python3-mypy-1.18.2-1.fc43.noarch

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, die verknüpfte mypy-play-Reproduktion und das gezeigte Beispiel mit --strict auszuführen, um den no-any-return-Fehler zu bestätigen. Verfolge, wie das vollständig typisierte Ergebnis von dict.get() im Umfeld von ifcls inferiert und eingegrenzt wird, füge dann Abdeckung für das erwartete Verhalten type[Self] | None hinzu und überprüfe, dass das Beispiel den Fehler nicht mehr meldet.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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