Flake8 Use f-string
Flake8-use-fstring is a Flake8 plugin designed to enforce the use of f-strings for string formatting within Python projects. It checks for instances where `%` formatting or the `.format()` method are used and suggests their replacement with f-strings. The current version is 1.4, and it sees active, though infrequent, maintenance releases, primarily for bug fixes and compatibility updates.
Warnings
- gotcha The `FS003` rule, which checks for missing 'f' prefixes on strings containing curly brackets, is disabled by default. It must be explicitly enabled using `--enable-extensions=FS003` (or `enable-extensions=FS003` in config) because it can produce false positives, especially with regular expressions.
- gotcha The plugin's 'greedy levels' (`--percent-greedy` and `--format-greedy`) for detecting string formatting can lead to false positives at higher levels (1 or 2) if the value immediately preceding `%` or `.format` is not a string literal. The default level 0 is safer but less aggressive.
- gotcha As of v1.4, `flake8-use-fstring` explicitly skips byte literals (strings prefixed with `b`) when enforcing f-string usage. This means it will not report errors for old-style formatting on byte strings.
- gotcha While `flake8-use-fstring` encourages f-strings, using them directly for logging messages (e.g., `logger.info(f"User: {user}")`) is generally discouraged. The Python `logging` module is optimized for deferred string formatting and structured logging when arguments are passed separately (e.g., `logger.info("User: %s", user)` or `logger.info("User: {}", user)`).
- compatibility Version 1.2 of `flake8-use-fstring` introduced support for Flake8 v4. If you are using an older version of Flake8, you may encounter compatibility issues or unexpected behavior.
Install
-
pip install flake8-use-fstring
Quickstart
import os
def old_style_formatting():
name = "World"
print("Hello, %s!" % name) # FS001
print("Hello, {}!".format(name)) # FS002
def missing_f_prefix():
# This will trigger FS003 if enabled
message = "User: {os.environ.get('USER', 'guest')}"
def fstring_example():
name = "Pythonista"
print(f"Hello, {name}!")
old_style_formatting()
missing_f_prefix()
fstring_example()
# To run this example:
# 1. Save the code above as `my_module.py`
# 2. Run flake8:
# $ flake8 my_module.py
#
# To see FS003 warnings, enable extensions:
# $ flake8 --enable-extensions=FS003 my_module.py
#
# For more aggressive checking (e.g., if 'name' was not a literal string):
# $ flake8 --percent-greedy=2 --format-greedy=2 my_module.py