| description | Python Scripting, Data Science, and Backend Standards. |
|---|---|
| applyTo | **.py, **.ipynb, **.requirements.txt, **.toml |
Enforce strict typing, modern Python practices, and cross-platform compatibility. You are fighting against the "it's just a script" mentality to ensure production-quality Python code.
Python is powerful but prone to "spaghetti code" without discipline. These instructions mandate strict type hinting, modern path handling, and robust testing to ensure our code is maintainable and safe on Windows and Linux alike.
- PEP 8: Adherence is mandatory. Use formatting tools like
black. - Typing: Strict Type Hints are MANDATORY (
typing,pydantic). Untyped code is legacy code. - Data Models: Use
@dataclassfor clear, memory-efficient data structures.
Example - Strong Typing:
from typing import List, Optional
def process_items(items: List[str]) -> Optional[int]:
if not items:
return None
return len(items)- The Rule: ❌ Banish
os.path.jointo the shadow realm. - The Solution: ✅
pathlibis non-negotiable.
Example - Pathlib:
from pathlib import Path
# 🛡️ Works safely on Windows and Linux
base_dir = Path("data")
file_path = base_dir / "user_logs" / "latest.log"
if file_path.exists():
content = file_path.read_text()- Assume
venvusage on Windows (.\venv\Scripts\activate). - Manage dependencies via
requirements.txtorpyproject.toml.
- Runner:
pytest. - Linting:
pylintorruff.
- Fixtures: Use
conftest.pyfor shared setup. - Parametrization: Use
@pytest.mark.parametrizefor data-driven tests. avoids code duplication.
Example - Parametrized Test:
import pytest
@pytest.mark.parametrize("input_val,expected", [
(1, 2),
(2, 4),
(10, 20),
])
def test_doubler(input_val, expected):
assert (input_val * 2) == expected- Wildcard Imports:
from module import *is forbidden. It pollutes the namespace. - Mutable Defaults: Never use mutable default arguments (
def func(a=[]):). - Print Debugging: Use the
loggingmodule, notprint().