Basic checking of format string compatibility in f-strings
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.
validate static format specifiers for known types like
float,int
I can't imagine this is very simple.
However it's definitely possible to check for __format__! I'm not sure what exact files are useful to check.
I think mypy actually supports this for .format calls, but not for f-strings. So hopefully shouldn't be too hard to get it working. Try looking at checkstrformat.py and checkexpr.py
Related / duplicate: #11723