python / python/mypy

Loop Variable over Literal List Not Recognised as Having Literal Type

Aperta
#18,826 6 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

When a for-loop is used to iterate over a list-literal (or other collection-literal) which contains only scalar literals, then MyPy should be smart enough to recognize that the implicit type of the loop variable is not merely the type of the values in the list but the specific values in that list.

To Reproduce

import typing as _tp

MyLiteral: _tp.TypeAlias = _tp.Literal["foo", "bar", "baz"]

def func(a1: MyLiteral):
    ...

def func2() -> None:
    a: MyLiteral
    a = "foo"
    func(a)
    a = "bar"
    func(a)

    b: MyLiteral
    for b in ["foo", "bar"]:
        func(b)

    for c in ["foo", "bar"]:
        func(c)

Expected Behavior

  • At a minimum, there should be no warnings emitted on the first loop: MyPy should be smart enough to identify that all the values the loop is assigning to b are compatible with its explicit type of MyLiteral, the same way it identifies that the values being assigned to a on lines 10 & 12 are legal.
  • Ideally, there should also be no warnings emitted on the second loop: it would be nice if MyPy correctly identified the implicit type of c as Literal["foo", "bar"], which is compatible with the first argument of func()

Actual Behavior

$ mypy [REDACTED]/tmp.py
[REDACTED]\tmp.py:16: error: Incompatible types in assignment (expression has type "str", variable has type "Literal['foo', 'bar', 'baz']")  [assignment]
[REDACTED]\tmp.py:20: error: Argument 1 to "func" has incompatible type "str"; expected "Literal['foo', 'bar', 'baz']"  [arg-type]
Found 2 errors in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: mypy 1.5.1 (compiled: yes)
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: Python 3.11.2

Related Issues

  • #9230: Issue complaining about the same problem, in the specific case where the loop variable is being used to access members of TypedDict. A fix was applied which solved the problem, but only for the special-case of accessing members of TypedDict, not for other, similar cases such as using the loop variable as a function argument as in the above example

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

Non viene indicato alcun file sorgente né alcun test. Inizia eseguendo con mypy la riproduzione Python segnalata e ispezionando i test esistenti sui tipi literal e sull’inferenza dei cicli; il lavoro è completato quando i casi con variabile di ciclo esplicita e implicita non producono errori, preservando il comportamento atteso di Literal.

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.