Logo de Designing Python Apis

Designing Python Apis

Comunidade
wdm0006
designing-python-apis

Projete APIs intuitivas para bibliotecas Python, seguindo princípios de simplicidade, consistência e facilidade de descoberta. Gerencie reexportações públicas, evolução da API, descontinuações, alterações incompatíveis e tratamento de erros. Use ao projetar ou revisar a API de uma biblioteca, expor um símbolo em um __init__ de pacote ou gerenciar versões e descontinuações da API.

Add to TypingMind

Visão geral

Publicado porwdm0006
Repositóriopython-skills
Nome da habilidadedesigning-python-apis
Estrelas
111
Forks
17
Arquivos incluídos
2
LicençaMIT
Links
  • Instruções em Markdown

    Um arquivo SKILL.md que o modelo carrega sob demanda, consumindo tokens apenas quando uma solicitação é realmente relevante para a habilidade.

  • Funciona com qualquer LLM

    As habilidades de IA são escritas em Markdown simples, não em código específico de um provedor. Por isso, funcionam com GPT, Claude, Gemini, Grok ou um modelo local.

  • Arquivos incluídos: 2

    Scripts, templates e referências que o modelo pode ler enquanto trabalha. Os arquivos são somente para leitura e nunca são executados.

  • Código aberto

    Publicada por wdm0006 no GitHub. Leia os arquivos da habilidade antes de instalá-la.

Instalação

Instale a habilidade de IA Designing Python Apis no TypingMind para usá-la com qualquer LLM ou adicione-a a outro agente que leia SKILL.md.

1

Instalar no TypingMind

O TypingMind instala uma habilidade diretamente da pasta dela no GitHub — lê o arquivo SKILL.md, reúne os arquivos de recursos em um pacote e armazena o resultado localmente.

  1. Abra o app e vá para Plugins → Habilidades.
  2. Escolha "Instalar do GitHub".
  3. Cole a URL abaixo, que aponta para a pasta da habilidade, e confirme.
    https://github.com/wdm0006/python-skills/tree/main/skills/python/api-design
  4. Ative a habilidade em cada chat em que quiser disponibilizá-la.
Plugins → Habilidades → Adicionar habilidade → Via URL do GitHub. Depois, cole a URL da pasta e pressione Continuar.
2

Instalar em outro agente

Qualquer agente que leia o formato Agent Skills pode usar esta habilidade — copie a pasta para o diretório de habilidades desse agente.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/wdm0006/python-skills.git /tmp/python-skills
mkdir -p .claude/skills
cp -r /tmp/python-skills/skills/python/api-design .claude/skills/designing-python-apis
Reinicie Claude Code após copiar para que a nova habilidade seja reconhecida.

Use no TypingMind

Ative Designing Python Apis em qualquer chat do TypingMind e o modelo cuida do resto. O nome e a descrição da habilidade ficam no prompt do sistema e, assim que uma solicitação relevante aparece, o modelo carrega as instruções completas automaticamente — sem precisar de acionamento manual e sem consumir tokens até que ela seja realmente usada.

O modelo carrega Designing Python Apis automaticamente assim que uma solicitação é relevante para essa habilidade.

Funciona com qualquer modelo de IA

Habilidades de IA são instruções em Markdown simples, não código específico de um provedor. Por isso, Designing Python Apis não fica vinculada ao modelo para o qual foi criada. Instale-a uma vez no TypingMind e use-a com GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama ou um modelo local executado por conta própria — tudo com suas próprias chaves de API.

  • Carregada apenas quando necessário

    O prompt do sistema contém apenas o nome e a descrição. As instruções são buscadas na primeira solicitação relevante, então uma habilidade sem uso não gera custo.

  • Troque de modelo durante a conversa

    Como a habilidade é composta de instruções, não de código, trocar de modelo não afeta seu funcionamento — o próximo modelo lê o mesmo arquivo SKILL.md.

Instruções da habilidade

Este é o conteúdo de SKILL.md que o modelo carrega. Leia antes de instalar — uma habilidade é um conjunto de instruções que seu modelo seguirá.

Python API Design

Core Principles

  1. Simplicity: Simple things simple, complex things possible
  2. Consistency: Similar operations work similarly
  3. Least Surprise: Behave as users expect
  4. Discoverability: Find via autocomplete and help

Progressive Disclosure Pattern

python
# Level 1: Simple functions
from mylib import encode, decode
result = encode(37.7749, -122.4194)

# Level 2: Configurable classes
from mylib import Encoder
encoder = Encoder(precision=15)

# Level 3: Low-level access
from mylib.internals import BitEncoder

Naming Conventions

python
# Actions: verbs
encode(), decode(), validate()

# Retrieval: get_*
get_user(), get_config()

# Boolean: is_*, has_*, can_*
is_valid(), has_permission()

# Conversion: to_*, from_*
to_dict(), from_json()

Error Handling

python
class MyLibError(Exception):
    """Base exception with helpful messages."""
    def __init__(self, message: str, *, hint: str = None):
        super().__init__(message)
        self.hint = hint

# Usage
raise ValidationError(
    f"Latitude must be -90 to 90, got {lat}",
    hint="Did you swap latitude and longitude?"
)

Fail Loud, Not Silent

The most expensive bugs are the ones where failure is indistinguishable from success. A caller who gets no error assumes everything worked. These patterns all turned a real failure into a silent wrong answer in shipped code — guard against every one.

Don't write the success sentinel on the failure path. An except block that sets the same state a successful run would makes failed jobs look complete.

python
# BAD — any failure is reported to the user as a finished result.
try:
    result = run_job()
    status = "READY"
except Exception:
    status = "READY"        # failure now looks identical to success

# GOOD — distinct terminal states; the UI/caller can react.
try:
    result = run_job()
    status = "READY"
except Exception:
    log.exception("job failed")
    status = "ERROR"

Don't swallow distinct failures into one generic message. A broad except Exception that returns "error: something went wrong" (or worse, an empty result) collapses parse errors, missing files, and bugs into the same opaque string — undebuggable and often mistaken for "no problems found." Catch the specific exceptions you can handle; let the rest propagate.

An empty/partial result is not an error signal. Returning [], an empty DataFrame, or "what I fetched before the connection dropped" looks like a valid answer. Pagination that returns partial pages on a mid-stream RequestError, then gets aggregated as if complete, produces silently wrong analytics. Either raise, or return an explicit "incomplete" marker the caller must check — never let truncation masquerade as the full set.

Meter external work where it actually happens. A quota or request budget charged once around list_all_items() undercounts whenever that helper follows pagination internally: one budget unit can hide ten HTTP requests. Spend at the lowest shared request boundary so every page, retry, and detail fetch is counted.

python
# BAD — the helper may issue an unbounded number of requests.
budget.spend()
items = client.list_all_items()

# GOOD — pagination cannot bypass the meter.
def request(method, url, *, budget, **kwargs):
    budget.spend()
    return http.request(method, url, **kwargs)

Keep the budget above the raw HTTP call if cache hits should be free, and below retry logic if every retry consumes provider quota. Test with a fake paginated transport that returns multiple pages and assert both the result values and the exact number of budget spends; a one-page fake cannot prove this contract.

A no-op on unexpected input is a silent corruption. Code that skips columns of the wrong type, ignores a key it doesn't recognize, or continues past a file it can't parse — with no error and no report — leaves the caller believing the operation applied. If you can't act on an input, say so (raise, warn, or return a per-item error list); don't quietly do nothing.

Validation errors must not leave partial mutations behind. An inplace=True API that renames caller-owned columns and only then validates another argument can raise the right exception while still corrupting the caller's next operation. Validate every parameter and precondition before the first mutation. When work cannot be validated up front, stage it on a copy and commit only after success.

python
# BAD — invalid max_fraction still changes the caller's dataframe.
def detect(data, *, max_fraction=0.1, inplace=True):
    target = data if inplace else data.copy()
    target.rename(columns={"time": "timestamp"}, inplace=True)
    if not 0 < max_fraction < 0.5:
        raise ValueError("max_fraction must be between 0 and 0.5")
    return analyze(target)

# GOOD — the error path is side-effect free.
def detect(data, *, max_fraction=0.1, inplace=True):
    if not 0 < max_fraction < 0.5:
        raise ValueError("max_fraction must be between 0 and 0.5")
    target = data if inplace else data.copy()
    target.rename(columns={"time": "timestamp"}, inplace=True)
    return analyze(target)

Pin the contract in tests: snapshot caller-owned state, trigger a late validation error with inplace=True, and assert the object is unchanged. Testing only the exception type misses the damaging half of this bug.

python
before = frame.copy(deep=True)
with pytest.raises(ValueError, match="max_fraction"):
    detect(frame, max_fraction=0.5, inplace=True)
pd.testing.assert_frame_equal(frame, before)

Filtering down to empty must never read as "all clear." When you narrow a rule set, check set, or work list and the filter yields nothing, an "evaluate all → 0 problems" path reports a perfect score while actually checking nothing. Guard the empty case explicitly:

python
selected = [r for r in rules if r.category in requested]
if not selected:                       # empty filter ≠ everything passed
    raise ValueError(f"no rules match {requested!r}")

Never fabricate a fallback that looks real. Substituting sample/random data when a fetch fails (so the UI "has something to show") presents invented numbers as genuine. Surface the failure instead; a visible error beats a plausible lie.

Don't discard the real output on a non-zero exit. A subprocess wrapper that returns f"Error: {stderr}" whenever returncode != 0 loses the answer for tools that exit non-zero by design and write results to stdout — reporting a successful run as an empty "Error: ". Inspect stdout and the actual exit semantics before deciding it failed.

Test the public import path, not only the implementation module

A package can expose two functions with the same name and only one can work:

python
# mylib/__init__.py
def initialize_parser() -> None:
    pass                         # stale placeholder

# mylib/parser.py
def initialize_parser() -> None:
    global _parser
    _parser = build_parser()     # real implementation

Internal tests that import mylib.parser.initialize_parser all pass, while the documented from mylib import initialize_parser call does nothing. This is an API break even though neither definition is individually invalid.

Re-export the canonical object instead of wrapping or copying it:

python
# mylib/__init__.py
from .parser import initialize_parser

__all__ = ["initialize_parser"]

Then test through the path users are told to import. An identity assertion is a cheap drift guard, and one behavior assertion proves the public route performs the required initialization:

python
import mylib
from mylib import parser

def test_public_initializer_is_canonical():
    assert mylib.initialize_parser is parser.initialize_parser
    mylib.initialize_parser()
    assert parser.is_initialized()

Apply the behavior check to convenience exports, compatibility adapters, console entry-point targets, and documented import snippets. Use identity only when the public name is intended to be a direct alias. Testing only the leaf module proves the implementation; it says nothing about whether the public API reaches it.

Deprecation

Deprecate gracefully: warn now, document the removal version, and remove only in a major release. The warning mechanics (including deprecating parameters, classes, and modules) and the migration-guide template are owned by the managing-python-releases skill — see ../release-management/MIGRATION.md.

Anti-Patterns

python
# Bad: Boolean trap
process(data, True, False, True)

# Good: Keyword arguments
process(data, validate=True, cache=False)

The mutable-default-argument trap (def f(x: list = [])) is covered by the improving-python-code-quality skill.

For detailed patterns, see:

Review Checklist

Naming:
- [ ] Clear, self-documenting names
- [ ] Consistent patterns throughout
- [ ] Boolean params read naturally

Parameters:
- [ ] Minimal required parameters
- [ ] Sensible defaults
- [ ] Keyword-only after positional clarity

Exports:
- [ ] Direct package exports reference the canonical implementation, not a stale stub
- [ ] Tests import through the documented public path and assert real behavior

Errors:
- [ ] Custom exceptions with context
- [ ] Helpful error messages
- [ ] Documented in docstrings
- [ ] Failures fail loud — no success sentinel on the error path
- [ ] Empty/partial results never masquerade as a complete answer
- [ ] No silent no-ops or fabricated fallback data
- [ ] Validation failures leave caller-owned inputs unchanged

Learn More

This skill is based on the Ergonomics section of the Guide to Developing High-Quality Python Libraries by Will McGinnis. See these posts for deeper coverage:

Arquivos incluídos

O modelo lê esses arquivos sob demanda enquanto a habilidade está carregada. Eles são disponibilizados para leitura e nunca são executados.

Perguntas frequentes

O que a habilidade de IA Designing Python Apis faz?

Projete APIs intuitivas para bibliotecas Python, seguindo princípios de simplicidade, consistência e facilidade de descoberta. Gerencie reexportações públicas, evolução da API, descontinuações, alterações incompatíveis e tratamento de erros. Use ao projetar ou revisar a API de uma biblioteca, expor um símbolo em um __init__ de pacote ou gerenciar versões e descontinuações da API.

Por que usar Designing Python Apis no TypingMind?

Porque basta instalar uma vez para usar com qualquer modelo. A habilidade Designing Python Apis é escrita em Markdown simples, e não em código específico de um provedor, então a mesma habilidade funciona com GPT-5, Claude, Gemini, Grok ou um modelo local — e é possível trocar de modelo no meio do chat sem que ela deixe de funcionar. No TypingMind, você usa suas próprias chaves de API e paga diretamente aos provedores, em vez de pagar uma assinatura por licença de usuário. Suas habilidades e chats permanecem no seu próprio armazenamento.

Como instalar Designing Python Apis no TypingMind?

Abra Plugins → Habilidades → Instalar do GitHub no TypingMind e cole https://github.com/wdm0006/python-skills/tree/main/skills/python/api-design. O TypingMind lê o arquivo SKILL.md, reúne os arquivos da habilidade e a instala para que possa ser ativada em cada chat.

Quais modelos de IA podem usar Designing Python Apis?

Qualquer modelo conectado no TypingMind. As habilidades de IA são instruções em Markdown simples, e não código específico de um provedor. Assim, GPT, Claude, Gemini, Grok e modelos locais podem carregar esta habilidade quando uma solicitação corresponder a ela.

Quantos modelos de IA posso usar com Designing Python Apis?

Quantos quiser. Desde que o modelo ofereça suporte a habilidades, é possível usar Designing Python Apis com ele — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama e outros — tudo no TypingMind com suas próprias chaves de API.

A habilidade de IA Designing Python Apis é gratuita?

Sim. A habilidade é publicada no GitHub por wdm0006 sob a licença MIT. O pagamento é feito apenas ao seu provedor de IA pelos tokens usados.

O que são habilidades de IA?

Uma habilidade de IA é um conjunto reutilizável de instruções que ensina um modelo de IA a realizar uma tarefa específica. Ela segue o formato aberto Agent Skills: um arquivo SKILL.md com nome e descrição, além de scripts, templates ou arquivos de referência de que o modelo possa precisar. O modelo lê as instruções apenas quando sua solicitação corresponde à habilidade, então uma habilidade instalada não gera custos até ser usada.

Qual é a diferença entre habilidades de IA e plugins ou servidores MCP?

Um plugin ou servidor MCP oferece ao modelo novas ferramentas que ele pode acionar — código que é executado em algum lugar e retorna um resultado. Já uma habilidade de IA dá ao modelo o conhecimento e as orientações de que ele precisa: como abordar uma tarefa, quais etapas seguir e como deve ser um bom resultado. As habilidades são escritas em Markdown simples, por isso não precisam de servidor, chave de API nem ambiente de execução, e funcionam com qualquer modelo.

Ver lista completa

Crie seu próprio espaço de trabalho com IA agora

Inscreva-se na nossa newsletter para receber avisos sobre novos recursos e futuros sorteios 👇