Skip to content

Basic checking of format string compatibility in f-strings #17714

Open
@nielsbuwen

Description

@nielsbuwen

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions