In this lesson, you will learn how to automate the enforcement of PEP 8 standards and clean up unused code across your entire project using the Ruff linter.
While mypy focuses on type safety, keeping your codebase clean, consistent, and free of "dead weight" is equally important for long-term maintainability. Ruff is an extremely fast, all-in-one tool that replaces older, slower linters like Flake8 and isort.
Setting Up Ruff
To get started, you configure Ruff in your pyproject.toml file. This acts as the single source of truth for your project’s style guide. You can specify which error codes to enforce and how to handle imports.
[tool.ruff]
# Set the line length to match your team's preference
line-length = 88
[tool.ruff.lint]
# E: PEP 8 errors, F: Pyflakes (logic errors), I: isort (import sorting)
select = ["E", "F", "I"]
[tool.ruff.lint.isort]
# Automatically group and sort imports
known-first-party = ["my_project"]
Enforcing Standards
Once configured, you can run ruff check . to identify issues. However, the true power of Ruff lies in its ability to automatically fix those issues for you. By running:
ruff check . --fix
Ruff will automatically:
- Remove unused imports: If you have an
importstatement that isn't being used in your module, Ruff deletes it. - Sort imports: It organizes your imports into standard library, third-party, and local groupings, ensuring consistency across your files.
- Correct PEP 8 violations: It fixes common stylistic errors, such as missing whitespace around operators or improper indentation.
By integrating this into your development workflow, you stop spending time in code reviews arguing about comma placement or sorting imports manually. Instead, you delegate these "mechanical" aspects of code quality to Ruff, allowing you to focus on the core logic and type-safe architecture of your application.
Key Takeaway: Use Ruff’s pyproject.toml configuration to automate PEP 8 compliance and import management, ensuring your entire codebase remains clean and consistent without manual intervention.