This demo covers Python code formatting, linting, and type checking using modern tools.
- Understand PEP8 style guidelines
- Use Ruff for linting and formatting
- Apply type hints and use mypy for type checking
PEP8 is the official Python style guide. Key points:
- Indentation: Use 4 spaces per indentation level
- Line length: Maximum 79-88 characters
- Imports: One per line, grouped (standard library, third-party, local)
- Whitespace: Around operators, after commas, not inside brackets
- Naming:
snake_casefor functions/variables,PascalCasefor classes
Ruff is an extremely fast Python linter and formatter that replaces multiple tools (flake8, black, isort, etc.).
With the Ruff VS Code extension installed:
- Automatic formatting on save - Code is formatted when you save
- Inline error highlighting - Problems appear as you type
- Quick fixes - Click the lightbulb icon for auto-fixes
# Check for linting issues
ruff check .
# Check a specific file
ruff check demos/01-code-style/bad_example.py
# Auto-fix issues where possible
ruff check --fix .
# Format code
ruff format .
# Format a specific file
ruff format demos/01-code-style/bad_example.py
# Check what would change without applying
ruff format --check .Open these two files side by side to see the difference:
| File | Description |
|---|---|
| bad_example.py | Code with PEP8 violations |
| good_example.py | The same code, properly formatted |
# See all issues in the bad example
ruff check demos/01-code-style/bad_example.py
# Format it and see the difference
ruff format demos/01-code-style/bad_example.pyType hints make code more readable and catch bugs early.
def greet(name: str) -> str:
return f"Hello, {name}!"
def calculate_average(numbers: list[float]) -> float:
return sum(numbers) / len(numbers)# Check a file
mypy demos/01-code-style/type_checking_demo.py
# Check with strict mode
mypy --strict demos/01-code-style/type_checking_demo.pySee type_checking_demo.py for examples of:
- Basic type hints
- Optional types
- Collection types
- Type aliases
- What mypy catches
All tool settings are in the root pyproject.toml:
[tool.ruff]
line-length = 88
target-version = "py312"
[tool.ruff.lint]
select = ["E", "W", "F", "I", "B", "C4", "UP"]
[tool.mypy]
python_version = "3.12"
disallow_untyped_defs = true- Consistency matters - Follow PEP8 for readable code
- Automate formatting - Let tools handle style, focus on logic
- Use type hints - Catch bugs before runtime
- Configure once -
pyproject.tomlstores all settings
Complete the task in tasks/01-code-style/ to practice refactoring messy code.