Chuyển đến nội dung
Skillpedia
API và máy chủ (backend)15k · #11023

python-design

Skill này làm gì

Skill đưa ra các quy tắc thiết kế cho script và công cụ Python. Dành cho lập trình viên muốn code dễ thay đổi và dễ hiểu.

Khi nào nên dùng

  • ✓Khi bạn viết hoặc thay đổi file Python, nhất là script dòng lệnh.
  • ✓Khi bạn lên kế hoạch tách một dự án Python thành các module.
  • ✓Khi bạn review code Python và muốn phát hiện vấn đề thiết kế.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/mindfold-ai/Trellis/blob/main/.agents/skills/python-design/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Hãy review script Python này và cho tôi biết thiết kế của nó đang rối ở đâu hoặc khó thay đổi ở chỗ nào.”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Agent áp dụng các quy tắc từ một cuốn sách thiết kế phần mềm nổi tiếng, chẳng hạn giữ các module sâu với giao diện đơn giản, và kiểm tra các dấu hiệu cảnh báo khiến code khó thay đổi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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)  
Câu hỏi thường gặp

Nó tìm những vấn đề nào?

Nó tìm các thay đổi lan ra nhiều nơi, gánh nặng tư duy lớn và những điều bất ngờ ẩn khiến code khó thay đổi an toàn.

Có chỉ dành cho ứng dụng web không?

Không. Skill được viết cho script và công cụ dòng lệnh, nên phù hợp nhất với các loại đó.

Nó có thêm tính năng mới không?

Không. Ý tưởng cốt lõi là quản lý độ phức tạp chứ không thêm tính năng.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
15k
Vị trí xếp hạng
#11023
Giấy phép
AGPL-3.0
Cập nhật
29/9/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự