본문으로 건너뛰기
Skillpedia
API 및 서버 (백엔드)15k · #11023

python-design

하는 일

스킬은 Python 스크립트와 도구의 설계 규칙을 제공합니다. 변경하기 쉽고 이해하기 쉬운 코드를 원하는 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓Python 파일, 특히 명령줄 스크립트를 작성하거나 바꿀 때.
  • ✓Python 프로젝트를 모듈로 나누는 방법을 계획할 때.
  • ✓Python 코드를 검토하면서 설계 문제를 찾고 싶은 경우.

스킬 링크

https://github.com/mindfold-ai/Trellis/blob/main/.agents/skills/python-design/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/mindfold-ai/Trellis/blob/main/.agents/skills/python-design/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“이 Python 스크립트를 검토하고, 설계가 어디서 엉키고 있어서 바꾸기 어려운지 알려 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트는 잘 알려진 소프트웨어 설계서의 규칙을 적용합니다. 예를 들어 단순한 인터페이스로 모듈을 깊게 유지하는 것이며, 코드를 바꾸기 어렵게 만드는 경고 신호를 점검합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Python Design for CLI Scripts

Design patterns and principles for writing maintainable Python CLI tools and utilities. Based on A Philosophy of Software Design (Ousterhout), adapted for scripting contexts.

When to Activate

  • Writing or modifying Python files
  • Planning module decomposition
  • Code review of Python changes
  • Refactoring scripts that feel "messy"
  • Adding a new subcommand or utility function

Core Thesis

The central challenge is managing complexity, not adding features.

Complexity is anything that makes code hard to understand or modify. It has three symptoms:

  1. Change Amplification — A small change requires edits in many places
  2. Cognitive Load — You must hold too much context to make a safe change
  3. Unknown Unknowns — You don't know what you don't know (the most dangerous)

Complexity is incremental. It accumulates through hundreds of small decisions, not one catastrophic mistake. Therefore: sweat the small stuff.


Principle 1: Deep Modules

A module's value is the ratio of functionality hidden vs. interface exposed.

Deep module (good):          Shallow module (bad):
┌──────────┐                 ┌──────────────────────────┐
│ simple   │                 │ complex interface        │
│ interface│                 │ many params, many methods │
├──────────┤                 ├──────────────────────────┤
│          │                 │                          │
│  rich    │                 │  thin implementation     │
│  impl    │                 │                          │
│          │                 └──────────────────────────┘
│          │
└──────────┘

Practical test: If a caller must understand how the module works internally to use it correctly, the module is too shallow.

Example: Task Data Access

# Shallow — caller must know JSON structure, file paths, error handling
def _read_json_file(path: Path) -> dict:
    with open(path, encoding="utf-8") as f:
        return json.load(f)

# Every caller does this independently:
task_path = tasks_dir / name / "task.json"
data = _read_json_file(task_path)
title = data.get("title") or data.get("name", "")
status = data.get("status", "planning")
assignee = data.get("assignee", "")
# Deep — caller gets what they need, module hides JSON/path/parsing
@dataclass(frozen=True)
class TaskInfo:
    name: str
    title: str
    status: str
    assignee: str
    priority: str
    directory: Path

def load_task(tasks_dir: Path, name: str) -> TaskInfo | None:
    """Load task by directory name. Returns None if not found."""
    ...

def list_active_tasks(tasks_dir: Path) -> list[TaskInfo]:
    """List all non-archived tasks, sorted by priority."""
    ...

The deep version absorbs complexity: JSON parsing, field defaults, directory scanning, archive filtering. Callers just work with typed data.


Principle 2: Type-First Development

Types define contracts before implementation. This workflow catches design problems early:

  1. Define data shapes — dataclass or TypedDict first
  2. Define function signatures — parameter and return types
  3. Implement to satisfy types — let the type checker guide completeness
  4. Validate at boundaries — runtime checks only where data enters the system

Frozen Dataclasses for Internal Data

from dataclasses import dataclass
from typing import Literal

@dataclass(frozen=True)
class AgentRecord:
    agent_id: str
    task_name: str
    worktree_path: Path
    platform: Literal["Codex", "codex", "cursor"]
    status: Literal["running", "done", "failed"]
    branch: str

Frozen dataclasses are immutable — no accidental mutation, safe to pass around.

TypedDict for External JSON Shapes

When the data comes from a file (task.json, config.yaml, registry.json), use TypedDict to document the expected shape:

from typing import TypedDict, Required, NotRequired

class TaskData(TypedDict):
    title: Required[str]
    status: Required[str]
    assignee: NotRequired[str]
    priority: NotRequired[str]
    parent: NotRequired[str]
    children: NotRequired[list[str]]

This eliminates scattered .get("field", default) calls — the shape is documented once.

NewType for Domain Primitives

When two strings mean different things, make the type system enforce it:

from typing import NewType

TaskName = NewType("TaskName", str)    # directory name like "03-10-v040"
BranchName = NewType("BranchName", str)  
자주 묻는 질문

어떤 문제를 찾나요?

여러 곳에 퍼지는 변경, 많은 인지 부담, 코드를 위험하게 만드는 숨은 부작용을 찾습니다.

웹 앱에만 맞나요?

아닙니다. 이 스킬은 스크립트와 명령줄 도구를 위해 작성되어, 그런 곳에 가장 잘 맞습니다.

새 기능을 추가하나요?

아닙니다. 핵심 생각은 기능을 추가하는 것이 아니라 복잡성을 관리하는 것입니다.

상세 정보

작성자의 원본 설명

Python design patterns for CLI scripts and utilities — type-first development, deep modules, complexity management, and red flags. Use when reading, writing, reviewing, or refactoring Python files, especially in .trellis/scripts/ or any CLI/scripting context. Also activate when planning module structure, deciding where to put new code, or doing code review.

repo: mindfold-ai/Trellis

인기도

GitHub 스타
15k
순위
#11023
라이선스
AGPL-3.0
업데이트
2026. 9. 29.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬