python / python/mypy

Basic checking of format string compatibility in f-strings

Aperta
#17,714 3 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Feature

Mypy should check whether format strings in f-strings make sense in basic cases.

Pitch

Consider this minimal example

print(f"{123:xyz}")

This fails at runtime with

Value Error: Invalid format specifier 'xyz' for object of type 'int'

But mypy does not find any problems.

Why is this a problem? Here is my real-world example:

In a temperature controlling function, we logged the current temperature vs the required temperature. Everything worked. Then we introduced a custom class Temperature to keep track of the unit (celsius in our case). We changed every function that accepted a float before to now accept a Temperature. Mypy was very helpful for this.

But unfortunately it did not warn about the logging calls that rounded the temperature to three digits:

print(f"Temperature now is {t:.3f}")

With t being a float this worked flawlessly and horribly broke at runtime when we changed the type of t to Temperature.

So my feature request consists of these parts:

  • forbid any format specifier for custom classes that don't implement __format__
  • validate static format specifiers for known types like float, int

If someone can point me to the right files, i can try to implement this myself.

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 vengono indicati file o test. Inizia individuando la gestione delle f-string da parte di mypy e il comportamento di format descritto nell'issue, quindi usa gli esempi con int, float e classi personalizzate come verifiche; il lavoro è completato quando le specifiche di formato non valide richieste vengono segnalate senza rifiutare i casi validi.

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

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Funzionalità
Difficoltà
5/5
Tempo stimato
Più di una settimana
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.