flake8-tidy-imports
A flake8 plugin that helps you write tidier imports by enforcing rules on import aliases, banned modules, and relative imports. It is currently at version 4.12.0, actively maintained, and supports Python versions 3.10 and newer. Releases typically occur a few times a year, with major versions introducing significant changes.
Warnings
- breaking Rule codes were renumbered in version 4.0.0. All rule codes were increased by 50 (e.g., I200 became I250).
- breaking Python 2 support was dropped in version 2.0.0.
- gotcha If `flake8`'s `select` option is defined, `flake8-tidy-imports` rules (I25x) must be explicitly added for the plugin to be active.
- gotcha The `banned-modules` configuration can use wildcards (`*`) to match zero or more path components. It also allows banning imported objects, not just modules.
- gotcha A special `{python2to3}` directive can be used within `banned-modules` to automatically ban a preselected list of Python 2-era modules and recommend their Python 3/six replacements.
Install
-
pip install flake8-tidy-imports
Quickstart
import os
# Example file: my_module.py
# import json as json # I250: Unnecessary import alias
# from datetime import timedelta as timedelta # I250: Unnecessary import alias
# from ..utils import helper # I252: Relative import from parent module (if configured)
# import mock # I251: Banned import 'mock' used - use unittest.mock instead. (if configured)
# Configure flake8 in setup.cfg or pyproject.toml
# [flake8]
# banned-modules =
# mock = use unittest.mock instead.
# django.utils.six = no more six!
# {python2to3}
# ban-relative-imports = parents
# select = I25
# To run flake8:
# flake8 my_module.py
# For demonstration purposes, this code is not meant to be run directly
# but shows common violations flake8-tidy-imports would catch.
# The actual plugin operates via the flake8 command-line tool.
print("Run 'flake8 <your_file.py>' after configuring flake8-tidy-imports.")