Flake8 Literal
flake8-literal is a Flake8 plugin designed to enforce consistent styling of string literals in Python code. It validates inline literals, multiline literals, and docstrings for quote usage (single or double quotes). Additionally, it includes checks for raw string usage, preventing unnecessary raw strings and enforcing their use when needed to avoid escaped backslashes. The current version is 1.5.0, and it is actively maintained.
Warnings
- gotcha flake8-literal is a plugin and does not expose symbols for direct import into Python code. Its functionality is integrated by running the `flake8` command-line tool. All configurations are done through `flake8`'s configuration files (e.g., `setup.cfg`, `.flake8`) or command-line options, not within Python code.
- gotcha The raw string validation feature for regular expression patterns (e.g., `L104`) has a specific limitation: it only works when string literals are directly passed as arguments to `re` module functions (e.g., `re.compile(r'...')`) and these functions are called directly (not aliased or stored in variables first). Indirect usages, like defining a pattern string in a variable and then passing it to `re.compile(pattern)`, will not be checked.
- gotcha As a `flake8` plugin, `flake8-literal`'s effectiveness can depend on the version of `flake8` being used. While `flake8-literal` requires Python >=3.12, ensure that your installed `flake8` version is compatible with this plugin and with your Python environment. Major updates to `flake8` can sometimes introduce changes in how plugins are discovered or configured.
Install
-
pip install flake8-literal
Quickstart
# Create a file named 'example.py'
# Then run flake8 example.py from your terminal
def check_quotes():
# L100: Use double quotes for inline literals (if configured)
inline_string = 'hello world'
# L101: Use single quotes for multiline literals (if configured)
multiline_string = """
This is a multiline string.
"""
# L102: Use double quotes for docstrings (if configured)
"""This is a docstring with incorrect quotes (if configured)."""
# L103: Unnecessary raw string (if configured to avoid escapes)
path_string = r"C:\users\name"
import re
# L104: Regex pattern should be a raw string (if configured strictly)
regex_pattern = re.compile('[a-z]')
# To configure flake8-literal, create a setup.cfg or .flake8 file:
# For example, in setup.cfg:
# [flake8]
# literal-inline-quotes = double
# literal-multiline-quotes = single
# literal-docstring-quotes = double
# literal-avoid-escape = true
# literal-raw-regex-always-raw = true