Python AI Coding Rules
Python's simplicity is deceptive — AI assistants often produce Python that works but is far from Pythonic, ignoring type hints, abusing mutable defaults, mixing concerns in modules, and skipping proper exception hierarchies. Python AI rules define the conventions that experienced Python developers rely on: type annotation standards, `dataclass` vs `TypedDict` usage, exception handling patterns, logging configuration, and project structure conventions. Whether you're building a Django web app, a FastAPI service, a data pipeline, or an ML model training script, well-crafted AI rules on AI Rules Hub ensure that Cursor and Copilot produce code that passes `mypy`, `ruff`, and `pylint` without modification.
Why Use AI Rules for Python?
- Require full type annotations so AI-generated code passes mypy strict mode
- Prevent mutable default argument bugs (a silent Python anti-pattern)
- Enforce `dataclass` or `Pydantic` models over raw dictionaries for structured data
- Standardise logging with `structlog` or the standard `logging` module — no bare `print()`
- Define naming conventions consistent with PEP 8 for modules, classes, and functions
Best Practices for Python AI Coding
Type-Annotate Everything
Instruct AI to add type annotations to all function signatures and class attributes, enabling IDE autocomplete and static analysis to catch bugs before runtime.
Use Pydantic for External Data
Rule AI to validate all external data (API inputs, config files, environment variables) through Pydantic models — never trust raw `dict` data from external sources.
Specific Exception Handlers
Prohibit bare `except:` clauses. AI should always catch specific exception types and re-raise or log with context.
Context Managers for Resources
Enforce `with` statements for file handles, database connections, and locks — never manually calling `.close()` or `.release()`.
Common Patterns & Standards
Dependency Injection via Constructors
Define service classes that receive dependencies (database sessions, HTTP clients) as constructor arguments rather than importing them globally.
Repository Pattern for ORM Queries
Wrap SQLAlchemy or Django ORM queries in repository functions to keep business logic decoupled from persistence details.
Async-First for I/O-Bound Services
For FastAPI or asyncio-based services, instruct AI to prefer `async def` for I/O-bound operations and `await` coroutine calls consistently.
Structured Project Layout
Enforce a consistent layout: `src/` package, `tests/` at root, `pyproject.toml` for config — making projects predictable across the team.
Top Python Rules on AI Rules Hub
Explore Related AI Rules
Share Your Python AI Rules
Have rules that improved your Python workflow? Submit them to AI Rules Hub and help the community get better results from AI coding assistants.
