Mypy not inferring return type of dict.get()
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
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
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo la riproduzione collegata di mypy-play e l’esempio mostrato con --strict per confermare l’errore no-any-return. Traccia come il risultato completamente tipizzato di dict.get() viene inferito e ristretto attorno a ifcls, quindi aggiungi la copertura per il comportamento previsto type[Self] | None e verifica che l’esempio non segnali più l’errore.
Scritto dal modello di indicizzazione a partire dal testo della issue.
Valutazione
- Stack tecnologico
- python
- Ambito
- tooling
- Tipo di issue
- Bug
- Difficoltà
- 4/5
- Tempo stimato
- 3-5 giorni
- Stato di attività
- Ferma
- Chiarezza
- Abbastanza chiara
- Idoneità per principianti
- 45/100