python-design
O que ela faz
A skill oferece regras de design para scripts e ferramentas Python. É para desenvolvedores que querem código fácil de mudar e fácil de entender.
Quando usar
- ✓Quando você escreve ou altera arquivos Python, especialmente scripts de linha de comando.
- ✓Quando você planeja como dividir um projeto Python em módulos.
- ✓Quando você revisa código Python e quer identificar problemas de design.
Link da skill
https://github.com/mindfold-ai/Trellis/blob/main/.agents/skills/python-design/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Revise este script Python e me diga onde o design está ficando bagunçado ou difícil de mudar.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente aplica regras de um livro conhecido de design de software, como manter módulos profundos com interfaces simples, e verifica sinais de alerta que tornam o código difícil de mudar.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do 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:
- Change Amplification — A small change requires edits in many places
- Cognitive Load — You must hold too much context to make a safe change
- 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:
- Define data shapes — dataclass or TypedDict first
- Define function signatures — parameter and return types
- Implement to satisfy types — let the type checker guide completeness
- 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)
Perguntas frequentes
Quais problemas ela procura?
Ela procura mudanças que se espalham por muitos lugares, carga mental alta e surpresas ocultas que tornam o código arriscado de mudar.
Ela serve só para apps web?
Não. A skill é escrita para scripts e ferramentas de linha de comando, então se encaixa melhor nelas.
Ela adiciona funcionalidades novas?
Não. A ideia central é controlar a complexidade, e não adicionar funcionalidades.
Detalhes
Descrição original do autor
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
Popularidade
- Estrelas no GitHub
- 15 mil
- Posição no ranking
- #11023
- Licença
- AGPL-3.0
- Atualizada em
- 29/09/2026
Comentários
- …
Mais skills deste repositório
first-principles-thinking
15 milAjuda seu agente a testar um plano ou design quebrando-o em verdades básicas e raciocinando a partir delas, em vez de depender do hábito ou da convenção.
trellis-before-dev
15 milAjuda seu agente a ler as diretrizes de código e as notas de tarefa do projeto antes de começar a escrever código, para que ele siga as convenções da equipe.
trellis-brainstorm
15 milAjuda seu agente a esclarecer uma nova funcionalidade ou uma tarefa pouco clara, fazendo uma pergunta útil por vez, verificando o código e combinando um escopo enxuto.
trellis-break-loop
15 milAjuda seu agente a analisar um bug depois de corrigido, descobrir o tipo de causa raiz e por que as correções anteriores falharam, e salvar lições para evitar repetição.
Skills parecidas
api-connector-builder
280 milFaz seu agente construir novas conexões com APIs seguindo o padrão já existente. Use quando precisar adicionar mais uma integração sem criar um novo jeito de fazer.
api-design
280 milAjuda seu agente a projetar APIs REST seguindo as melhores práticas. É útil para definir como as APIs se comunicam, como os erros são mostrados e como organizar os dados.
backend-patterns
280 milAjuda seu agente com padrões de arquitetura do lado do servidor e otimização de banco de dados. É útil para construir ou revisar o código que roda no servidor.