Basic checking of format string compatibility in f-strings
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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