python / python/mypy

mypy doesn't narrow `Final` objects in nested contexts

Aperta
#19,080 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-final
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

I have a global constant I've marked with Final. In a class definition, I use this constant to swap out implementations of a method. While inside a type guarding block, but outside the method definition, the type of the Final object is narrowed, but inside of the method it is not narrowed.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.12&gist=2d4c97cffea1dd6710bf5cc7283f7290

from typing import *

def _init() -> None | str:
    return None

RESOLVE_X: Final = _init()

class Example:
    
    if RESOLVE_X is not None:
        
        reveal_type(RESOLVE_X)  # note: Revealed type is "builtins.str"
        
        def __str__(self) -> str:
            return RESOLVE_X  # error: Incompatible return value type (got "str | None", expected "str")  [return-value]
            
    else:
        def __str__(self) -> str:
            return "example"

Expected Behavior

Inside the __str__ definition in the if RESOLVE_X is not None: block, RESOLVE_X should stay narrowed as it cannot be reassigned and have its type re-widened in the future.

Actual Behavior

main.py:12: note: Revealed type is "builtins.str"
main.py:15: error: Incompatible return value type (got "str | None", expected "str")  [return-value]
Found 1 error in 1 file (checked 1 source file)

Your Environment

Mypy version 1.15.0.
Python 3.12.

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Inizia con la riproduzione di mypy-play collegata nell’issue ed eseguila nell’ambiente indicato con Python 3.12 e mypy 1.15.0. Traccia come viene gestito il type guard per il Final a livello di modulo nel corpo della classe rispetto alla definizione annidata di str. Il lavoro è completato quando il narrowing rivelato viene preservato all’interno di str e l’esempio passa senza l’errore relativo al valore restituito.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Tranquilla
Chiarezza
Abbastanza chiara
Idoneità per principianti
48/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.