Search code examples
pythonflaskstring-formattingflask-wtforms

Why does f-string literal not work here, whereas %()s formatting does?


I am trying to format my validator message with the min/max values in the actual validator.

Here's my Flask Form:

class MyForm(FlaskForm):
    example = IntegerField(label=('Integer 0-10'),
              validators=[InputRequired(), NumberRange(min=0, max=10, message="must be between %(min)s and %(max)s!")])

Using message="must be between %(min)s and %(max)s!" gives me the expected output:

must be between 0 and 10!

Whereas using message=f"must be between {min} and {max}!" gives me the output:

must be between <built-in function min> and <built-in function max>!

How can I use f-string formatting for my validator message? Is this something related to f-string evaluating at run-time? I don't fully understand the concept behind it, I just know it's the preferred way to string format.


Solution

  • "must be between %(min)s and %(max)s!" is a string literal that Flask will later perform a search-and-replace on, while f"must be between {min} and {max}!" is a simpler and more efficient way to say "must be between " + str(min) + " and " + str(max) + "!". That evaluates to the string you described.