Logo von Designing Python Apis

Designing Python Apis

Community
wdm0006
designing-python-apis

Entwirft intuitive Python-Bibliotheks-APIs nach den Grundsätzen Einfachheit, Konsistenz und Auffindbarkeit. Behandelt öffentliche Re-Exports, die Weiterentwicklung von APIs, Deprecations, Breaking Changes und Fehlerbehandlung. Verwenden Sie diesen Skill beim Entwerfen oder Überprüfen einer Bibliotheks-API, beim öffentlichen Bereitstellen eines Symbols über ein Paket-__init__ oder beim Verwalten von API-Versionen und Deprecations.

Add to TypingMind

Übersicht

Herausgeberwdm0006
Repositorypython-skills
Skill-Namedesigning-python-apis
Sterne
111
Forks
17
Mitgelieferte Dateien
2
LizenzMIT
Links
  • Anweisungen in Markdown

    Eine SKILL.md-Datei, die das Modell bei Bedarf lädt. So werden nur dann Token verbraucht, wenn eine Anfrage tatsächlich dazu passt.

  • Funktioniert mit jedem LLM

    KI-Skills bestehen aus reinem Markdown, nicht aus anbieterspezifischem Code. Daher funktionieren sie mit GPT, Claude, Gemini, Grok oder einem lokalen Modell.

  • Mitgelieferte Dateien: 2

    Skripte, Vorlagen und Referenzmaterial, die das Modell bei der Arbeit lesen kann. Die Dateien sind schreibgeschützt und werden niemals ausgeführt.

  • Open Source

    Von wdm0006 auf GitHub veröffentlicht. Prüfen Sie vor der Installation die Quelldateien.

Installation

Installieren Sie den KI-Skill Designing Python Apis in TypingMind, um ihn mit jedem LLM zu nutzen, oder fügen Sie ihn einem anderen Agenten hinzu, der SKILL.md lesen kann.

1

In TypingMind installieren

TypingMind installiert einen Skill direkt aus seinem GitHub-Ordner. Dabei liest die App SKILL.md, bündelt die Ressourcendateien und speichert das Ergebnis lokal.

  1. Öffnen Sie die App und gehen Sie zu Plugins → Skills.
  2. Wählen Sie „Von GitHub installieren“.
  3. Fügen Sie die unten angegebene URL des Skill-Ordners ein und bestätigen Sie.
    https://github.com/wdm0006/python-skills/tree/main/skills/python/api-design
  4. Aktivieren Sie den Skill in jedem Chat, in dem er verfügbar sein soll.
Plugins → Skills → Skill hinzufügen → Über GitHub-URL. Fügen Sie dann die Ordner-URL ein und klicken Sie auf „Weiter“.
2

In einem anderen Agenten installieren

Jeder Agent, der das Agent-Skills-Format unterstützt, kann diesen Skill nutzen. Kopieren Sie den Ordner in das Skill-Verzeichnis des jeweiligen Agenten.

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
Starten Sie Claude Code nach dem Kopieren neu, damit der neue Skill erkannt wird.

In TypingMind verwenden

Aktivieren Sie Designing Python Apis in einem beliebigen Chat in TypingMind. Den Rest übernimmt das Modell. Name und Beschreibung des Skills stehen im System-Prompt. Sobald eine Anfrage passt, lädt das Modell selbstständig die vollständigen Anweisungen — Sie müssen den Skill nie manuell aufrufen, und er verbraucht erst Token, wenn er tatsächlich genutzt wird.

Das Modell lädt Designing Python Apis automatisch, sobald eine passende Anfrage gestellt wird.

Funktioniert mit jedem KI-Modell

KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher ist Designing Python Apis nicht an das Modell gebunden, für das der Skill geschrieben wurde. Installieren Sie ihn einmal in TypingMind und nutzen Sie ihn mit GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder einem selbst betriebenen lokalen Modell — alles mit Ihren eigenen API-Schlüsseln.

  • Wird nur bei Bedarf geladen

    Der System-Prompt enthält nur den Namen und die Beschreibung. Die Anweisungen werden bei der ersten passenden Anfrage geladen. Ein ungenutzter Skill verursacht daher keine Kosten.

  • Modell im laufenden Chat wechseln

    Da der Skill aus Anweisungen statt aus Code besteht, funktioniert er auch nach einem Modellwechsel — das nächste Modell liest dieselbe SKILL.md-Datei.

Skill-Anweisungen

Dies ist der Inhalt von SKILL.md, den das Modell lädt. Lesen Sie ihn vor der Installation — ein Skill besteht aus Anweisungen, denen Ihr Modell folgt.

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:

Mitgelieferte Dateien

Das Modell liest diese Dateien bei Bedarf, während der Skill geladen ist. Sie werden als lesbare Dateien bereitgestellt und niemals ausgeführt.

Häufig gestellte Fragen

Was macht der KI-Skill Designing Python Apis?

Entwirft intuitive Python-Bibliotheks-APIs nach den Grundsätzen Einfachheit, Konsistenz und Auffindbarkeit. Behandelt öffentliche Re-Exports, die Weiterentwicklung von APIs, Deprecations, Breaking Changes und Fehlerbehandlung. Verwenden Sie diesen Skill beim Entwerfen oder Überprüfen einer Bibliotheks-API, beim öffentlichen Bereitstellen eines Symbols über ein Paket-__init__ oder beim Verwalten von API-Versionen und Deprecations.

Warum Designing Python Apis in TypingMind nutzen?

Weil Sie den Skill einmal installieren und mit jedem Modell verwenden können. Designing Python Apis besteht aus reinem Markdown statt aus anbieterspezifischem Code. So funktioniert derselbe Skill mit GPT-5, Claude, Gemini, Grok oder einem lokalen Modell – und Sie können das Modell mitten im Chat wechseln, ohne dass der Skill seine Funktion verliert. TypingMind verwendet Ihre eigenen API-Schlüssel. Sie bezahlen die Anbieter daher direkt statt über ein Abonnement pro Nutzerplatz, und Ihre Skills und Chats bleiben in Ihrem eigenen Speicher.

Wie installiere ich Designing Python Apis in TypingMind?

Öffnen Sie in TypingMind Plugins → Skills → Von GitHub installieren und fügen Sie https://github.com/wdm0006/python-skills/tree/main/skills/python/api-design ein. TypingMind liest die Datei SKILL.md, bündelt die zugehörigen Dateien und installiert alles als Skill, den Sie für jeden Chat einzeln aktivieren können.

Welche KI-Modelle können Designing Python Apis nutzen?

Jedes Modell, das Sie mit TypingMind verbinden. KI-Skills bestehen aus reinen Markdown-Anweisungen statt aus anbieterspezifischem Code. Daher können GPT, Claude, Gemini, Grok und lokale Modelle diesen Skill laden, wenn eine Anfrage dazu passt.

Wie viele KI-Modelle kann ich mit Designing Python Apis verwenden?

So viele Sie möchten. In TypingMind können Sie Designing Python Apis mit jedem Modell verwenden, das Skills unterstützt, etwa mit GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama. Dabei nutzen Sie Ihre eigenen API-Schlüssel.

Ist der KI-Skill Designing Python Apis kostenlos?

Ja. Der Skill wird von wdm0006 auf GitHub unter der Lizenz MIT veröffentlicht. Sie bezahlen nur Ihren eigenen KI-Anbieter für die verwendeten Token.

Was sind KI-Skills?

Ein KI-Skill ist ein wiederverwendbares Anweisungspaket, das einem KI-Modell vermittelt, wie es eine bestimmte Aufgabe erledigt. Es folgt dem offenen Format Agent Skills: Die Datei SKILL.md enthält den Namen und die Beschreibung des Skills. Hinzu kommen bei Bedarf Skripte, Vorlagen oder Referenzdateien für das Modell. Das Modell liest die Anweisungen nur, wenn Ihre Anfrage zum Skill passt. Ein installierter Skill verursacht daher erst Kosten, wenn er verwendet wird.

Wie unterscheiden sich KI-Skills von Plugins oder MCP-Servern?

Ein Plugin oder MCP-Server stellt einem Modell neue aufrufbare Tools bereit – Code, der auf einem System ausgeführt wird und ein Ergebnis zurückgibt. Ein KI-Skill vermittelt dem Modell stattdessen Wissen und Vorgehensweisen: wie es eine Aufgabe angeht, welche Schritte es befolgt und wie eine gute Ausgabe aussieht. Skills bestehen aus reinem Markdown und kommen daher ohne Server, API-Schlüssel und Laufzeitumgebung aus. Sie funktionieren mit jedem Modell.

Alle anzeigen

Jetzt eigenen KI-Arbeitsbereich einrichten

Abonnieren Sie unseren Newsletter und erfahren Sie mehr über neue Funktionen und kommende Gewinnspiele 👇