python / python/mypy

Basic checking of format string compatibility in f-strings

Open
#17,714 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

feature
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No files or tests are named. Start by locating mypy's handling of f-strings and the format behavior described in the issue, then use the int, float, and custom-class examples as checks; done means the requested invalid format specifications are reported without rejecting valid cases.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
devtools
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.