Skip to content

code-yeongyu/oh-my-openagent / packages/shared-skills/skills/programming

programming

Unverified

Applies strict, modern language practice (typed errors, exhaustive match, tests that can fail) for Python, Rust, TypeScript, JavaScript, and Go. Use for work on .py, .rs, .ts, .js, or .go files, and whenever a test or spec file is written, reshaped, reviewed, or deleted: the four-question test authoring gate and the junk-test classes live here.

FileKindSize
SKILL.mdskill md33.3 KB
references/code-smells.mdmarkdown13.9 KB
references/go/README.mdmarkdown7.7 KB
references/go/backend-stack.mdmarkdown16.6 KB
references/go/bootstrap.mdmarkdown8.9 KB
references/go/bubbletea-v2.mdmarkdown11.3 KB
references/go/cobra-stack.mdmarkdown11.5 KB
references/go/concurrency.mdmarkdown10.9 KB
references/go/data-modeling.mdmarkdown12.0 KB
references/go/error-handling.mdmarkdown10.1 KB
references/go/golangci-strict.mdmarkdown10.0 KB
references/go/grpc-connect.mdmarkdown10.3 KB
references/go/libraries.mdmarkdown13.7 KB
references/go/one-liners.mdmarkdown5.5 KB
references/go/sqlc-pgx.mdmarkdown12.7 KB
references/go/testing.mdmarkdown14.2 KB
references/go/type-patterns.mdmarkdown9.5 KB
references/logging.mdmarkdown10.5 KB
references/python/README.mdmarkdown15.7 KB
references/python/async-anyio.mdmarkdown14.2 KB
references/python/data-modeling.mdmarkdown6.6 KB
references/python/data-processing.mdmarkdown4.2 KB
references/python/error-handling.mdmarkdown6.0 KB
references/python/fastapi-stack.mdmarkdown9.2 KB
references/python/httpx2-optimization.mdmarkdown12.0 KB
references/python/libraries.mdmarkdown10.6 KB
references/python/one-liners.mdmarkdown7.9 KB
references/python/orjson-stack.mdmarkdown13.3 KB
references/python/pydantic-ai.mdmarkdown8.2 KB
references/python/pyproject-strict.mdmarkdown9.0 KB
references/python/textual-tui.mdmarkdown5.1 KB
references/python/type-patterns.mdmarkdown4.1 KB
references/rust-ub/README.mdmarkdown9.9 KB
references/rust-ub/miri-sanitizers-loom.mdmarkdown11.5 KB
references/rust-ub/ub-taxonomy.mdmarkdown13.3 KB
references/rust/README.mdmarkdown16.6 KB
references/rust/api-design.mdmarkdown6.5 KB
references/rust/async-tokio.mdmarkdown12.6 KB
references/rust/axum-stack.mdmarkdown14.2 KB
references/rust/cargo-strict.mdmarkdown10.0 KB
references/rust/clap-stack.mdmarkdown12.1 KB
references/rust/concurrency.mdmarkdown14.3 KB
references/rust/libraries.mdmarkdown17.4 KB
references/rust/macros.mdmarkdown3.3 KB
references/rust/one-liners.mdmarkdown7.5 KB
references/rust/proptest-insta.mdmarkdown13.9 KB
references/rust/type-state.mdmarkdown13.1 KB
references/rust/unsafe-discipline.mdmarkdown12.9 KB
references/rust/zero-cost-safety.mdmarkdown16.9 KB
references/testing/README.mdmarkdown10.3 KB
references/testing/junk-classes.mdmarkdown6.2 KB
references/typescript/README.mdmarkdown10.6 KB
references/typescript/backend-hono.mdmarkdown21.2 KB
references/typescript/bootstrap.mdmarkdown6.9 KB
references/typescript/data-modeling.mdmarkdown5.0 KB
references/typescript/error-handling.mdmarkdown4.7 KB
references/typescript/oxc-lint.mdmarkdown7.6 KB
references/typescript/tsconfig-strict.mdmarkdown3.9 KB
references/typescript/type-patterns.mdmarkdown5.2 KB
scripts/go/check-no-excuse-rules.shexecutablescript7.1 KB
scripts/go/new-project.tsscript6.8 KB
scripts/go/templates/.editorconfigother206 B
scripts/go/templates/.golangci.ymlconfig1.5 KB
scripts/go/templates/AGENTS.md.tmplother845 B
scripts/go/templates/README.md.tmplother207 B
scripts/go/templates/Taskfile.ymlconfig706 B
scripts/go/templates/ci.ymlconfig863 B
scripts/go/templates/config.goscript643 B
scripts/go/templates/gitignoreother99 B
scripts/go/templates/main.go.tmplother329 B
scripts/go/templates/run.goscript350 B
scripts/python/check-no-excuse-rules.pyscript24.9 KB
scripts/python/new-project.tsscript6.7 KB
scripts/python/new-script.tsscript4.2 KB
scripts/rust/check-no-excuse-rules.shexecutablescript7.5 KB
scripts/rust/check-no-excuse-rules.test.tsscript3.4 KB
scripts/rust/new-project.tsscript6.1 KB
scripts/scaffolders.test.tsscript4.9 KB
scripts/shared/run-tool.tsscript855 B
scripts/typescript/check-no-excuse-rules.test.tsscript4.0 KB
scripts/typescript/check-no-excuse-rules.tsscript13.1 KB
scripts/typescript/check-test-junk-rules.tsscript5.5 KB
scripts/typescript/check-test-junk.test.tsscript4.9 KB
scripts/typescript/check-test-junk.tsscript5.4 KB
scripts/typescript/mutation-proof.test.tsscript1.9 KB
scripts/typescript/mutation-proof.tsscript6.4 KB
scripts/typescript/new-project.test.tsscript6.8 KB
scripts/typescript/new-project.tsscript3.1 KB
scripts/typescript/oxc/.oxfmtrc.jsonconfig256 B
scripts/typescript/oxc/.oxlintrc.jsonconfig1.7 KB
scripts/typescript/oxc/lint/oxlint-plugin/LICENSEother1.0 KB
scripts/typescript/oxc/lint/oxlint-plugin/index.jsscript288 B
scripts/typescript/oxc/lint/oxlint-plugin/no-em-dash-copy.jsscript785 B
scripts/typescript/oxc/lint/oxlint-plugin/require-suppression-reason.jsscript2.3 KB
scripts/typescript/oxc/tsconfig.jsonconfig794 B

references/python/data-modeling.md

View on GitHub
# Data Modeling

Which container to use, how to structure data, and why frozen is the default.

---

## Decision flowchart

```
Is it a fixed set of named constants?
  YES → StrEnum / IntEnum
  NO ↓
Is it just branding a primitive (int, str, float)?
  YES → NewType("X", base)
  NO ↓
Is it an interface / contract ("this thing can do X")?
  ├─ Shape only, no shared code → Protocol
  └─ Shared method implementation needed → ABC
  NO ↓
Does the data cross a trust boundary (user input, API, file, external DB)?
  YES → pydantic.BaseModel (frozen=True) — validates + serializes
  NO ↓
Is it a dict shape needed for JSON compat / **kwargs typing?
  YES → TypedDict
  NO ↓
Is it structured data with named fields?
  YES → @dataclass(frozen=True, slots=True)
  NO ↓
Is it a tuple with positional semantics (x, y coords / DB row)?
  YES → NamedTuple
  NO → you probably don't need a new type
```

---

## Container reference

### @dataclass — internal value object

The default for structured data inside your codebase. Zero overhead, no framework coupling.

```python
from dataclasses import dataclass
from typing import NewType

UserId = NewType("UserId", int)

@dataclass(frozen=True, slots=True)
class User:
    id: UserId
    name: str
    email: str

@dataclass(frozen=True, slots=True)
class Point:
    x: float
    y: float
```

Always `frozen=True, slots=True`. Mutable only when mutation is the documented purpose — opt out with `# noqa: MUTABLE_OK`.

### Pydantic BaseModel — trust boundary guardian

Use when data enters or leaves your system. Validates at construction, serializes to JSON, generates OpenAPI schema.

```python
from pydantic import BaseModel, ConfigDict, EmailStr

class CreateUserRequest(BaseModel):
    model_config = ConfigDict(frozen=True)

    name: str
    email: EmailStr
    age: int

class UserResponse(BaseModel):
    model_config = ConfigDict(frozen=True)

    id: int
    name: str
    email: str
```

**The one rule**: data crosses a trust boundary → Pydantic. Everything else → dataclass.
Never use Pydantic for internal-only data just because it's convenient. The validation cost is real.

### TypedDict — dict that knows its shape

Use when the value must stay a `dict` at runtime — JSON blobs, `**kwargs`, third-party APIs expecting dicts.

```python
from typing import TypedDict, NotRequired

class Headers(TypedDict):
    content_type: str
    authorization: NotRequired[str]

def make_request(url: str, headers: Headers) -> None: ...

make_request("https://api.example.com", {"content_type": "application/json"})
```

### Protocol — structural interface

"Anything that has method X" — no inheritance required.

```python
from typing import Protocol

class Renderable(Protocol):
    def render(self) -> str: ...

class Saveable(Protocol):
    async def save(self) -> None: ...

@dataclass(frozen=True, slots=True)
class MarkdownDoc:
    content: str
    def render(self) -> str:
        return self.content

def publish(doc: Renderable) -> None:
    print(doc.render())  # MarkdownDoc works — no inheritance needed
```

Default to Protocol for interfaces. ABC only when you need shared method implementations.

### ABC — interface with shared code

Only when Protocol isn't enough.

```python
from abc import ABC, abstractmethod

class BaseRepository(ABC):
    @abstractmethod
    async def get(self, id: int) -> Model | None: ...

    @abstractmethod
    async def save(self, model: Model) -> None: ...

    async def get_or_raise(self, id: int) -> Model:
        result = await self.get(id)
        if result is None:
            msg = f"{type(self).__name__}: id {id} not found"
            raise LookupError(msg)
        return result
```

### NamedTuple — positional + named (rare)

Only when you need tuple protocol (unpacking, indexing).

```python
from typing import NamedTuple

class Coordinate(NamedTuple):
    x: float
    y: float

x, y = Coordinate(1.0, 2.0)  # tuple unpacking
```

99% of the time, `@dataclass(frozen=True, slots=True)` is better.

---

## Quick lookup

| Situation | Use | Why |
|---|---|---|
| User input, API request/response | `Pydantic BaseModel` | Validation, JSON schema, serialization |
| DB row ↔ Python (ORM) | SQLAlchemy `Mapped[]` model | ORM integration, async session |
| Internal value object | `@dataclass(frozen=True, slots=True)` | Zero overhead, no validation needed |
| Multiple outcomes from function | Union of frozen dataclasses | Distinct types for `match` |
| Dict shape for JSON / `**kwargs` | `TypedDict` | Stays a dict at runtime |
| Fixed constants | `StrEnum` / `IntEnum` | Exhaustive match, no typos |
| Distinct primitive | `NewType("X", int)` | Zero runtime cost, type-level only |
| Contract / capability | `Protocol` | Structural typing, no inheritance |
| Contract + shared impl | `ABC` | When Protocol isn't enough |

---

## Comparison matrix

| Feature | dataclass | Pydantic | TypedDict | Protocol | NamedTuple | NewType | Enum |
|---|---|---|---|---|---|---|---|
| Validation | - | ✓ | - | - | - | - | - |
| JSON serialization | manual | built-in | native dict | - | - | - | `.value` |
| Immutable | frozen=True | frozen=True | - (dict) | N/A | always | N/A | always |
| Runtime cost | ~zero | validation | zero | zero | ~zero | zero | ~zero |
| `match` support | ✓ | ✓ | - | - | ✓ | - | ✓ |
| `slots` support | ✓ | - | - | - | - | - | - |

---

## Parse, don't validate

Validate at the boundary. Inside the boundary, types are proof of validity.

```python
# BAD — validate then pass raw data
def process_email(email: str) -> None:
    if "@" not in email:
        raise ValueError("invalid email")
    # still a raw str everywhere downstream

# GOOD — parse into typed value at boundary
from typing import NewType

Email = NewType("Email", str)

def parse_email(raw: str) -> Email:
    if "@" not in raw or "." not in raw.split("@")[1]:
        msg = f"invalid email: {raw}"
        raise ValueError(msg)
    return Email(raw.lower().strip())

# Downstream only sees Email, never raw str
def send_welcome(email: Email) -> None: ...
```

With Pydantic this happens automatically — `EmailStr` is already a parsed type. Once constructed, `.email` is always valid. No re-validation needed.

---

## Sources

- Python docs: [dataclasses](https://docs.python.org/3/library/dataclasses.html)
- Pydantic v2: [docs.pydantic.dev](https://docs.pydantic.dev/latest/)
- Python docs: [typing — Protocol](https://docs.python.org/3/library/typing.html#typing.Protocol)
- Python docs: [typing — TypedDict](https://docs.python.org/3/library/typing.html#typing.TypedDict)
- Alexis King: [Parse, don't validate](https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/)
finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the workStars: 318kUpdated Claude CodeCodexUnverifiedInstall
systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixesStars: 318kUpdated Claude CodeCodexUnverifiedInstall
test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation codeStars: 318kUpdated Claude CodeCodexUnverifiedInstall
skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy.Stars: 196kUpdated Claude CodeCodexVerifiedInstall