cityhive / rules
Cursor rule2 starsChanged 18 months agoMITArchived repositoryView on GitHub
Python Coding Standards
Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.
Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository6 other files it gives its agents.
- .cursor/rules/always-enable-context7.mdcCursor rule
- .cursor/rules/cursor-rules.mdcCursor rule
- .cursor/rules/dependency-management.mdcCursor rule
- .cursor/rules/project-overview.mdcCursor rule
- .cursor/rules/project-patterns.mdcCursor rule
- .cursor/rules/testing-guidelines.mdcCursor rule
The file
Show its rules and text
We split this python-standards.mdc into the rules it gives an agent
14 rules. About 0 are common, 6 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈6
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 8
For Python files: Follow these standards for consistent, maintainable code.
- Very specific: line 14
Avoid
Anytype: - use specific types or protocols - Very specific: line 28
Async functions: Use async def for I/O operations
- Distinctive: line 29
Await database calls: All SQLAlchemy operations must be awaited
- Very specific: line 48
Request handlers: Always accept web.Request, return web.Response
- Very specific: line 49
Template decorators: Use @aiohttp_jinja2.template() for HTML responses
- Distinctive: line 72
Comprehensions: Prefer over loops when readable
- Very specific: line 89
Error chaining: Use raise ... from err for context
- Very specific: line 91
HTTP exceptions: Use web.HTTPException subclasses
- Very specific: line 107
Use structlog infrastructure: Import from cityhive.infrastructure.logging
- Distinctive: line 108
Structured key-value pairs: Never use f-strings or % formatting
- Distinctive: line 109
Context binding: Use logger.bind() for related operations
- Distinctive: line 149
Middleware functions: Follow aiohttp middleware pattern
- Very specific: line 181
Logging imports: Always use from cityhive.infrastructure.logging import get_logger
≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
---
description: Python Coding Standards
globs: **/*.py
alwaysApply: false
---
# Python Coding Standards
**For Python files:** Follow these standards for consistent, maintainable code.
## Type System
- **Type hints required** on all functions and class methods
- **Use modern syntax**: `list[str]` not `List[str]`, `str | None` not `Optional[str]`
- **Avoid `Any` type** - use specific types or protocols
```python
# ✅ DO:
def process_items(items: list[dict[str, str]]) -> list[str]:
return [item["name"] for item in items]
# ❌ DON'T:
def process_items(items):
return [item["name"] for item in items]
```
## Async Programming
- **Async functions**: Use `async def` for I/O operations
- **Await database calls**: All SQLAlchemy operations must be awaited
- **Type hint async returns**: `-> Awaitable[ReturnType]` for complex cases
```python
# ✅ DO: Proper async handler
async def get_user(request: web.Request) -> web.Response:
async with request.app[db_key]() as session:
result = await session.execute(select(User).where(User.id == user_id))
user = result.scalar_one_or_none()
return web.json_response({"user": user.dict() if user else None})
# ❌ DON'T: Sync operations in async context
async def get_user(request: web.Request) -> web.Response:
session.execute(select(User)) # Missing await
```
## aiohttp Patterns
- **Use AppKey**: Type-safe application data storage
- **Request handlers**: Always accept `web.Request`, return `web.Response`
- **Template decorators**: Use `@aiohttp_jinja2.template()` for HTML responses
```python
# ✅ DO: Type-safe app keys
config_key = web.AppKey("config", Config)
app[config_key] = config
# ✅ DO: Proper handler signature
async def handler(request: web.Request) -> web.Response:
config = request.app[config_key]
return web.json_response({"status": "ok"})
# ✅ DO: Template rendering
@aiohttp_jinja2.template("page.html")
async def page_handler(request: web.Request) -> dict[str, Any]:
return {"title": "Page Title"}
```
## Code Style
- **Line length**: 88 characters maximum (Ruff default)
- **Function structure**: Guard clauses first, happy path last
- **Naming**: Descriptive names, no abbreviations (`user_count` not `uc`)
- **Comprehensions**: Prefer over loops when readable
```python
# ✅ DO: Guard clauses first
def calculate_discount(price: float, user_type: str) -> float:
if price <= 0:
raise ValueError("Price must be positive")
if user_type not in ["premium", "standard"]:
raise ValueError("Invalid user type")
# Happy path
return price * (0.1 if user_type == "premium" else 0.05)
```
## Error Handling
- **Specific exceptions**: `ValueError`, `TypeError` over generic `Exception`
- **Error chaining**: Use `raise ... from err` for context
- **Early returns**: Handle errors at function start
- **HTTP exceptions**: Use `web.HTTPException` subclasses
```python
# ✅ DO: Proper error chaining
try:
result = await risky_operation()
except APIError as e:
raise ProcessingError("Failed to process data") from e
# ✅ DO: HTTP exceptions
if not user:
raise web.HTTPNotFound(text="User not found")
```
## Logging
- **Use structlog infrastructure**: Import from `cityhive.infrastructure.logging`
- **Structured key-value pairs**: Never use f-strings or % formatting
- **Context binding**: Use logger.bind() for related operations
- **Request context**: Automatically handled by middleware
```python
# ✅ DO: Structured logging with key-value pairs
from cityhive.infrastructure.logging import get_logger
logger = get_logger(__name__)
logger.info("User created", user_id=12345, email="user@example.com")
logger.warning("Rate limit exceeded", user_id=12345, limit=100, current=105)
logger.error("Database connection failed", error="timeout", retry_count=3)
# ✅ DO: Context binding for related operations
user_logger = logger.bind(user_id=12345, session_id="abc-123")
user_logger.info("Login attempt", success=True)
user_logger.info("Page viewed", page="/dashboard")
# ✅ DO: Exception logging with structured data
try:
risky_operation()
except Exception as e:
logger.exception(
"Operation failed",
operation="data_processing",
error_type=type(e).__name__,
user_id=user_id,
)
# ❌ DON'T: String formatting or f-strings in logs
logger.info(f"Processing user {user_id}") # Bypasses structured logging
logger.info("Processing user %s", user_id) # Old format, not structured
print(f"Debug: {some_value}") # Never use print()
```
## Functions and Classes
- **Pure functions preferred** - clear inputs/outputs, no side effects
- **Classes only for**: Data models (Pydantic), external clients, complex state
- **No global state** - pass dependencies explicitly
- **Middleware functions**: Follow aiohttp middleware pattern
```python
# ✅ DO: Proper middleware pattern with structured logging
from cityhive.infrastructure.logging import get_logger
@web.middleware
async def logging_middleware(
request: web.Request,
handler: Handler
) -> web.StreamResponse:
logger = get_logger(__name__)
start_time = request.loop.time()
response = await handler(request)
duration = request.loop.time() - start_time
logger.info(
"Request completed",
method=request.method,
path=request.path,
status=response.status,
duration_seconds=round(duration, 3),
)
return response
```
## Imports
- **Absolute imports**: `from cityhive.domain import User`
- **Group imports**: stdlib, third-party, local (Ruff handles this)
- **No star imports**: `from module import *` forbidden
- **Logging imports**: Always use `from cityhive.infrastructure.logging import get_logger`
```python
# ✅ DO: Proper import organization
# Standard library imports
import asyncio
import json
from datetime import datetime
# Third-party imports
from aiohttp import web
from pydantic import BaseModel
# First-party imports
from cityhive.domain.models.user import User
from cityhive.infrastructure.logging import get_logger
logger = get_logger(__name__)
```
---
**Reference Implementation:**
- [Logging Guide](mdc:docs/logging.md) for structured logging patterns
- [Architecture Guide](mdc:docs/architecture.md) for clean architecture patterns
- [Development Guide](mdc:docs/development.md) for tooling and workflows
- [Testing Guidelines](mdc:.cursor/rules/testing-guidelines.mdc) for test patterns
- [Ruff configuration](mdc:pyproject.toml) for linting rules
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

