agentleFS
sergeyklaysergeyklay/cityhive/.cursor/rules/python-standards.mdc

cityhive / rules

Cursor rule2 starsChanged 18 months agoMITArchived repositoryView on GitHub

Python Coding Standards

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
  1. Distinctive:

    For Python files: Follow these standards for consistent, maintainable code.

    line 8
  2. Very specific:

    Avoid Any type: - use specific types or protocols

    line 14
  3. Very specific:

    Async functions: Use async def for I/O operations

    line 28
  4. Distinctive:

    Await database calls: All SQLAlchemy operations must be awaited

    line 29
  5. Very specific:

    Request handlers: Always accept web.Request, return web.Response

    line 48
  6. Very specific:

    Template decorators: Use @aiohttp_jinja2.template() for HTML responses

    line 49
  7. Distinctive:

    Comprehensions: Prefer over loops when readable

    line 72
  8. Very specific:

    Error chaining: Use raise ... from err for context

    line 89
  9. Very specific:

    HTTP exceptions: Use web.HTTPException subclasses

    line 91
  10. Very specific:

    Use structlog infrastructure: Import from cityhive.infrastructure.logging

    line 107
  11. Distinctive:

    Structured key-value pairs: Never use f-strings or % formatting

    line 108
  12. Distinctive:

    Context binding: Use logger.bind() for related operations

    line 109
  13. Distinctive:

    Middleware functions: Follow aiohttp middleware pattern

    line 149
  14. Very specific:

    Logging imports: Always use from cityhive.infrastructure.logging import get_logger

    line 181

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
python-standards.mdc
---
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

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.