Redocly/redocly-cli / packages/client-generator/eject-assets/skills/python-generator
python-generator
UnverifiedDesign of the ejected Redocly `python` client generator. Read it, and update it, before changing generators/python/.
The python generator — its skill
This file is the DESIGN of your ejected python generator (generators/python/):
to change the generator, edit this skill first, then make the code match it — a diff
to generators/python/ that has no covering sentence here is incomplete.
What it emits
One self-contained <stem>.py: typed dataclass models, a sync Client and an async
AsyncClient, and the embedded runtime. Python ≥ 3.9; the only dependency is
httpx (pip install httpx).
Design decisions that must hold
-
The file name is an importable module name. The
--outputstem follows the TypeScript convention (openapi.client.ts), andopenapi.client.pycannot be imported by name — nor can hyphens or a leading digit. The stem is converted withidentifierFor(stem, snake), sorebilly-core.client.tsemitsrebilly_core_client.pyandimport rebilly_core_clientjust works. -
Models are dataclasses by default, required fields first (a dataclass constraint), optionals
Optional[T] = None. Wire names live in a_field_map: ClassVar[Dict[str, str]]; decode/encode is reflective (_decode.py,get_type_hints) — no per-model codecs. -
The file passes
mypy --strict. It lands in the user's own package, so their strictest checker reads it: every function is annotated, the operation table is typed, and a decoded body iscastto the declared return type (decodereturnsAny). -
A
writeOnlyproperty is optional even when required: requests and responses share one model, and a response never carries it. It isOptional[T] = None, so a response decodes without it and a request still sends it. -
models: pydanticemitsBaseModelclasses instead, for the FastAPI-shaped half of the ecosystem that expects them. A wire name becomesField(alias=…)withpopulate_by_name=True, so_field_mapis not emitted in this mode — the alias is the mapping. Everything else is unchanged: the same class names, the same field names, the sameOptional[T] = None, the same enums and union aliases, the same client and runtime. Switching modes must not change a call site. -
A discriminated union carries its discriminator into the pydantic annotation. The decoder hands a whole object tree to
model_validate, so a union nested in a model is resolved by pydantic and never reaches theDISCRIMINATORStable that dataclass mode walks. Pydantic resolves it correctly fromAnnotated[Union[...], Field(discriminator=…)], which it accepts only when every member types that property as aLiteral— and the mapping already pins one value per member, so the members getLiteral["cat"]. Such a union registers no table entry: pydantic owns it at every depth, and theLiteralmakes the decoder's member probe exact. A union whose members never declare the property keeps the plainUnionand the table entry, and pydantic then matches nested members its own way — the description is what has to change there. -
One runtime serves both model modes.
_decode.pydispatches on the target: a class withmodel_validateis validated by pydantic, a dataclass is hydrated reflectively, andencodemirrors that withmodel_dump(by_alias=True, exclude_none=True, mode="json"). A second runtime variant per mode would double the surface that has to stay in step, and pydantic'sValidationErroralready subclassesValueError, so union member probing needs no new except clause. -
models: pydanticadds a dependency, and the header says so. The default mode keeps httpx as the only requirement; the pydantic header asks for both. A mode that quietly needed a package the file never named would fail at import with nothing to act on. -
Every parameter is its own argument, so their names share one namespace with the arguments the method declares itself (
body,headers,timeout,retry,idempotency_key). Build them withuniqueIdentifiers(..., { taken: … }): OpenAPI lets one operation use a name in two locations (idin the path AND in the query), and adefthat declared one name twice is aSyntaxError. The wire name is untouched, so the request is unchanged. -
Naming: fields/methods snake*case via
identifierFor(..., RESERVED_WORDS.python); reserved words get a trailing underscore (class*);+1/-1becomeplus_1/minus_1. -
Enums are
class X(str, Enum)with SCREAMING members; unions areUnion[...]aliases, emitted after the classes and the other aliases they name, because a module-level assignment evaluates at import. A DISCRIMINATED union registers its dispatch table in the runtime'sDISCRIMINATORSregistry (DISCRIMINATORS[Pet] = ("petType", {"cat": Cat, ...})), anddecode()routes through it —isinstancenarrowing works on decoded members. Undiscriminated unions decode by trying each member in order (the first that hydrates wins — see_decode.py). allOf is flattened viaflattenAllOf. -
Auth keys match the other languages.
auth={"apiKey": {...}}is the documented key — the same spelling TypeScript and PHP use, and the same as the scheme kind — withapi_keyaccepted as an alias so a snake_case config keeps working. -
Errors:
errorModemaps to raisingApiError(default) or returning aResultdataclass — the only generator with both modes outside TypeScript. -
Dates:
dateType: Dateannotatesformat: date-timeasdatetimeanddateasdate;_decode.pyparses ISO strings into them andencode()writesisoformat()back. The default (string) keeps the wire shape. -
Response headers: an operation that DECLARES success-response headers gains a
<op>_with_headers()variant (sync and async) returningEnvelope[T]—data,headers(coerced to int/bool/str with snake_case keys; absent/unparsable values omitted), and the rawresponse. Operations without declared headers get no variant, and the base method stays body-only. -
Servers: when the description declares servers, a
Serversclass is emitted with one static method per server; server VARIABLES become keyword arguments defaulting to the spec's defaults (Servers.production(organization_id="org_x")), so templated base URLs need no manual string building. The client's baked default staysservers[0]with variable defaults substituted. -
Stream bodies pass through. For an untyped
multipart/form-dataoperation (isUntypedMultipartBody) or a binary operation (isBinaryContentType), the body argument isAny, and a body that isbytes/bytearray, astr, a file-like object (a callable.read), or an iterator/async iterator of bytes goes to httpxcontent=, never throughjson=orto_multipart; adictbody of an untyped multipart operation keeps theto_multipartpath. The runtime sets the operation's declared content type only when the caller set none (matched case-insensitively), and never for a multipart body, whose boundary is the caller's. A body that cannot be replayed (a file-like object or iterator, as opposed tobytesorstr) is sent in exactly one attempt, whatever the retry policy says. The per-attempttimeoutstill applies. Both the sync and the asyncsendbehave the same. Typed multipart bodies are unaffected: they go straight toto_multipartand never through stream detection, so a model field namedreadcannot turn one into a raw upload. -
Parity surface: auth (bearer/basic/apiKey), retries with
Retry-After+ jittered backoff, timeouts, idempotency keys, middleware, pagination (<op>_pages()/<op>_items()+aitermirrors), SSE (iter_sse/aiter_sse), multipart. -
The runtime is hand-written in
runtime/*.pyin this folder and embedded as strings at prepare time — generator code never builds runtime logic from templates. Under--runtime modulethe same sources are written as sibling_*.pyfiles instead (package-relative imports become sibling imports; the client star-imports each module). -
on_settledsees every sent call once. Bothsend()andsend_async()call each middleware'son_settled(context, call)after the last attempt, wherecallholds the finalresponseor theerror,attempts, andduration_ms(from the first attempt to the end of theon_responsehooks). A timeout isApiTimeoutError; a cancelled async call isasyncio.CancelledError. A call that fails inon_requestdoes not reach it. Every hook runs; on a successful call the first hook exception fails the call, and on a failed call the original error wins. SSE streams open outsidesend(), so they reach no middleware. -
Telemetry is opt-in at generation time. With
client.telemetry: onthe generator also writes<module>_telemetry.py(fromtelemetry/telemetry.pyin this folder, embedded at prepare time) beside the client, in both runtime modes, with the generator version baked in. The client file does not change. The module imports nothing from the client; the application passestelemetry(sdk_name=..., sdk_version=..., client=...)in the client'smiddleware, and the open window is sent at interpreter exit. A timeout of the caller, such asasyncio.wait_for, cancels the task like any cancel, so it counts asaborted; only the client's owntimeoutcounts astimeout. -
Authored ONLY with the neutral toolkit (
Printer, naming, schema, pagination helpers) — the dogfooding guard fails otherwise. -
It documents itself. With
client.docs(or--docs), thedocshook writes<stem>.python.md: the security schemes, then one section per operation with its parameters, body, response type, and behavior notes. The call snippets come from this generator's ownsamplehook, so the page can only show the syntax of the SDK beside it, and the layout comes fromrenderReferencePagein the authoring toolkit — reachable from an ejected copy through@redocly/client-generator. Pagination on the page is decided bypaginationRuleFor, the same helper this generator resolves pagination with.
The modify loop
- Edit this skill: state the new behavior or decision.
- Make
generators/python/match it. - Run
redocly generate-clientand inspect thegit diffof the generated output — generated files are never hand-edited.
Newer built-in versions merge in with redocly eject-generator python --update.
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| brainstormingobra/superpowersYou MUST use this before any creative work - creating features, building components, adding functionality, modifying behavior, or planning anything new, in software or out of it (a talk, a business, a renovation). | Stars: 319k | Updated | Claude CodeCodex | Verified | Install |
| brand-guidelinesanthropics/skillsApplies Anthropic's official brand colors and typography to any sort of artifact that may benefit from having Anthropic's look-and-feel. Use it when brand colors or style guidelines, visual formatting, or company design standards apply. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| frontend-designanthropics/skillsGuidance for distinctive, intentional visual design when building new UI or reshaping an existing one. Helps with aesthetic direction, typography, and making choices that don't read as templated defaults. | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |
| mcp-builderanthropics/skillsGuide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when building MCP servers to integrate external APIs or services, whether in Python (FastMCP) or Node/TypeScript (MCP SDK). | Stars: 196k | Updated | Claude CodeCodex | Verified | Install |