🧹 Python Tutorial β€” Linting & Formatting (Clean, Consistent Code)

Introduction 🌟

Linting & Formatting help you maintain clean, readable, and error-free code. They enforce consistent style and catch bugs before runtime.

Note

πŸ’‘ Linter β†’ finds errors & bad patterns
πŸ’‘ Formatter β†’ auto-formats code
πŸ’‘ Essential for professional codebases, CI/CD, teams

1. Popular Linters & Formatters πŸ› οΈ

ToolPurpose
Flake8Linter (style + errors)
PylintVery strict linter
BlackOpinionated code formatter
isortSorts imports automatically
autopep8Auto-format to fit PEP8

2. Install Linting & Formatting Tools πŸ“¦

install_tools.sh

pip install flake8 black isort autopep8 pylint

3. Using Flake8 (Linting) πŸ”

flake8_run.sh

flake8 my_project/

βœ” Checks for PEP8 violations, unused imports, undefined variables.

Common Errors

  • E501 β†’ Line too long
  • F401 β†’ Unused import
  • F821 β†’ Undefined variable

4. Flake8 Configuration βš™οΈ

setup.cfg

[flake8]
max-line-length = 100
exclude = .git,__pycache__,venv
ignore = E203, W503

βœ” Add to setup.cfg or .flake8

5. Using Black (Auto Formatter) πŸ–€

black_format.sh

black my_project/

βœ” Black reformats all code in a consistent way automatically.

Black Configuration

pyproject.toml

[tool.black]
line-length = 100
target-version = ['py39']
exclude = '''
/(
    \.git
    | \.pytest_cache
    | venv
)/
'''

6. Using isort (Sort Imports) πŸ”„

isort.sh

isort my_project/

pyproject.toml (isort)

[tool.isort]
profile = "black"

βœ” Ensures import order: stdlib β†’ third-party β†’ local

7. Using autopep8 (Alternative Formatter) ✨

autopep8.sh

autopep8 --in-place --recursive my_project/

8. Using Pylint (Strict Linting) 🧠

pylint.sh

pylint my_project/

Pylint scores your code (0–10) and reports detailed issues.

9. Editor Integration 🧰

VS Code Settings Example

settings.json

{
  "python.linting.enabled": true,
  "python.linting.flake8Enabled": true,
  "python.formatting.provider": "black",
  "editor.formatOnSave": true
}

βœ” Formats on every save!

10. Pre-Commit Hooks (Automate linting before commit) πŸͺ

install_precommit.sh

pip install pre-commit

.pre-commit-config.yaml

repos:
  - repo: https://github.com/psf/black
    rev: stable
    hooks:
      - id: black

  - repo: https://github.com/PyCQA/flake8
    rev: 6.1.0
    hooks:
      - id: flake8

  - repo: https://github.com/pycqa/isort
    rev: 5.12.0
    hooks:
      - id: isort

precommit_install.sh

pre-commit install

βœ” Automatically formats & lints before every commit.

11. Example Workflow πŸ§ͺ

Here’s how a professional project handles linting & formatting:

  • 1️⃣ Sort imports β†’ isort
  • 2️⃣ Format code β†’ black
  • 3️⃣ Lint code β†’ flake8
  • 4️⃣ Fix remaining issues

12. Example Bad vs Good Code 🎯

Bad Code

bad.py

import os,sys

def add(a, b):return a+b

Good Code (Black + isort)

good.py

import os
import sys


def add(a, b):
    return a + b

13. Combined pyproject.toml Setup πŸ“˜

pyproject.toml

[tool.black]
line-length = 100

[tool.isort]
profile = "black"

[flake8]
max-line-length = 100
ignore = ["E203", "W503"]

Best Practices πŸ’‘

  • βœ” Always format before committing
  • βœ” Use Black + isort together for consistency
  • βœ” Automate everything with pre-commit hooks
  • βœ” Configure flake8 to avoid false positives
  • βœ” Use Pylint only for strict code quality assessment

Conclusion πŸŽ‰

>>β€œLinting finds problems. Formatting fixes them. Together, they make your Python code beautiful and professional.” ✨

You now understand Linting & Formatting in Python! Want the next topic? Try Testing (pytest), CI/CD Pipelines, Code Quality Tools, or Type Checking (Mypy). Just tell me! 😊