← Docs
Recipe

Recipe: Python class writer from spec

Generate a complete Python class from a natural-language specification. Meridian reads your spec, infers attributes and methods, and emits production-ready code with type hints and docstrings.

Input

Write a Python class called CacheManager that:
- Stores items with a TTL
- Supports get, set, delete, clear
- Evicts expired items on access
- Uses a dict backend
- Thread-safe with a lock

Output

import threading
import time
from typing import Any, Optional

class CacheManager:
    """Thread-safe TTL cache backed by a dict."""

    def __init__(self) -> None:
        self._store: dict[str, tuple[Any, float]] = {}
        self._lock = threading.Lock()

    def _evict_expired(self) -> None:
        now = time.monotonic()
        expired = [k for k, (_, exp) in self._store.items() if exp <= now]
        for k in expired:
            del self._store[k]

    def get(self, key: str) -> Optional[Any]:
        with self._lock:
            self._evict_expired()
            entry = self._store.get(key)
            if entry is None:
                return None
            value, _ = entry
            return value

    def set(self, key: str, value: Any, ttl: float = 300.0) -> None:
        with self._lock:
            self._store[key] = (value, time.monotonic() + ttl)

    def delete(self, key: str) -> None:
        with self._lock:
            self._store.pop(key, None)

    def clear(self) -> None:
        with self._lock:
            self._store.clear()

How it works

  • 1.Parses the spec for class name, attributes, and method contracts.
  • 2.Infers types from context and applies Python type hints.
  • 3.Generates docstrings and thread-safety primitives when requested.
  • 4.Emits a single self-contained file ready for production.

Tip: Add "with error handling" to your spec and Meridian will wrap methods in try/except blocks with custom exception types.