The Python target-language layer for Skmtc generators (@skmtc/lang-python). It covers the projection base factories, PySnippet, the register shapes with deferred imports, the five identifier kinds, relative imports from export paths, the head and value render model, and the producers for classes, functions, bodies and indentation. Use ALONGSIDE skmtc-generator whenever a generator writes Python.
Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Skmtc Lang Python?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/skmtc-skmtc-lang-python)
---
name: skmtc-lang-python
version: 0.1.0
description: >
The Python target-language layer for Skmtc generators
(@skmtc/lang-python). It covers the projection base factories,
PySnippet, the register shapes with deferred imports, the five
identifier kinds, relative imports from export paths, the head and
value render model, and the producers for classes, functions, bodies
and indentation. Use ALONGSIDE skmtc-generator whenever a generator
writes Python.
metadata:
describes:
'@skmtc/lang-python': '0.1'
---
# The Python layer (@skmtc/lang-python)
Read `skmtc-generator` first. The two worked examples are
`@skmtc/gen-pydantic` (a model generator) and `@skmtc/gen-httpx-pydantic`
(an SDK: an Index for each resource, and an accumulator for the client).
Generated code targets Python 3.12 or later.
## 1. Declare the language
The import graph declares the language. `src/base.ts` imports a factory,
and each snippet extends `PySnippet`.
```ts fragment
import { sanitizeIdentifier, snakeCase, toPyModelProjectionBase } from '@skmtc/lang-python'
export const PydanticBase = toPyModelProjectionBase<EnrichmentSchema>({
id: denoJson.name,
toIdentifierName({ ref }) {
return sanitizeIdentifier(toModelName(ref, (name) => camelCase(name, { upperFirst: true })))
},
toIdentifierType(ref, context) {
const schema = context.resolveSchemaRefOnce(ref)
return schema.type === 'object' && !isEmpty(schema.properties ?? {})
? { type: 'class' }
: { type: 'type-alias' }
},
toExportPath({ ref, enrichments, variant }) {
const name = this.toIdentifierName({ ref, enrichments, variant })
return `@/types/${sanitizeIdentifier(snakeCase(name))}.py`
},
})
```
The factories are `toPyModelProjectionBase`,
`toPyOasOperationProjectionBase` and `toPyOasOperationIndexBase`. An
Index is a `class` whose body gets a `def` for each operation.
## 2. An export path is a module
Each folder and file name of an export path is a part of a module name.
- **Set `settings.generatedSuffix` to `""` in `skmtc.config.json`.** The
default gives `pet.generated.py`, and Python reads that dot as a
package. `PyFile` throws when a file gets such a path, and the message
names the setting.
- A part must be a Python identifier and not a keyword. Write
`sanitizeIdentifier(snakeCase(name))` in `toExportPath`.
- `'@/'` is the project's `basePath`: point it at the folder of the
Python package. The hand-written files (`__init__.py`, base classes)
are in the same folder.
## 3. Register shapes
| Caller | Call | File |
|---|---|---|
| Projection | `this.register(args)` | Its own export file |
| Projection | `this.registerInto(path, args)` | The file you name |
| Snippet | `this.register({ ...args, destinationPath })` | The file you name |
`args` is `{ imports?, deferredImports?, definitions?, custom? }`. There
is no `reExports`.
- `imports: { pydantic: ['BaseModel'] }` renders
`from pydantic import BaseModel`. An alias is
`{ name: 'Field', alias: 'F' }`. A module with an empty list renders
`import module`.
- A module that is an export path (`'@/types/pet.py'`) renders as a
relative import: `from .pet import Pet`, `from ..types.pet import Pet`.
The engine registers this import for each model you refer to.
- The file renders its imports in three sorted groups: `__future__`,
modules from outside the project, and the project's own modules.
Register `__future__: ['annotations']` in each file that annotates with
a name from the project.
### Deferred imports
Two modules that import each other in their headers cannot load. For a
reference inside a cycle, register the same import as a deferred import:
```ts fragment
if (modelRef.suspended || modelRef.inCycle) {
this.register({
deferredImports: { [modelRef.settings.exportPath]: [this.name] },
destinationPath,
})
}
```
The statement then renders below the definitions of the file, in place
of the import in the header. This needs
`from __future__ import annotations` in the file.
## 4. Identifier kinds
| Kind | Factory | Renders |
|---|---|---|
| `class` | `createClass(name)` | `class Pet` + value |
| `type-alias` | `createTypeAlias(name)` | `type PetStatus = ` + value |
| `variable` | `createVariable(name, { typeName? })` | `name = ` + value |
| `def` | `createFunction(name)` | `def name` + value |
| `async-def` | `createFunction(name, { async: true })` | `async def name` + value |
- The kind does not change an import: every Python import has one form.
- A `type` statement reads its value when it is used. A type alias can
name a definition that comes later, and itself.
- Python has no keyword for visibility. `exported` and `noExport` render
nothing: a private name starts with an underscore.
## 5. Head and value
The identifier renders the head of a declaration, and the value renders
all that follows. The value of a `class` is a `PyClassValue`, and the
value of a `def` is a `PyFunctionValue`. A projection holds one and
renders it:
```ts fragment
this.value = new PyClassValue({
bases: ['BaseModel'],
description: objectSchema.description,
members: [...this.fields, this.extraFields],
})
override toString(): string {
return `${this.value}`
}
```
- The docstring is the first statement of a body. Pass `description`,
not a comment above the definition.
- A decorator renders above the head. The value carries them: give the
class a `decorators` field (`decorators = ['cached_property']`).
- A body with no statements renders `pass`.
## 6. Indentation
In Python, indentation is syntax. A producer renders its own lines from
column 0. `PyBody` and `PyIndented` are the only code that writes
indentation, and they indent each line of what they hold. Blocks nest, so
do not write leading spaces in a template.
A `PyBody` reads its statements when it renders. Give the body of an
Index the Index's `definitions` array: the members arrive after the
constructor.
## 7. Producers
| Producer | Renders |
|---|---|
| `PyList.toArguments(items)`, `.toLines`, `.toUnion` | `a, b`, one item on each line, `A \| B` |
| `PySubscript({ value, items })` | `list[Pet]`, `Literal["a", "b"]` |
| `PyCall({ callee, args })`, `PyKeywordArgument({ name, value })` | `Field(alias="petId")` |
| `PyDict(entries)`, `PyDictEntry({ key, value })` | `{"petId": pet_id}` |
| `PyParameter({ name, type?, defaultValue? })` | `limit: int \| None = None` |
| `PyParameters({ positional, keywordOnly })` | `self, pet_id: int, *, limit: int \| None = None` |
| `PyDocstring(text)` | `"""text"""`, or nothing |
An item that is `undefined` or `null` is absent. `PyParameters` writes
the `*` marker only when a keyword-only parameter follows it.
## 8. Names and literals
- `snakeCase(name)` for a module, a function, a parameter and an
attribute. Core's `camelCase(name, { upperFirst: true })` for a class.
- `sanitizeIdentifier(name)` makes any string a valid identifier: a
keyword gets a trailing underscore (`class_`).
- `toStringLiteral(value)` writes a string from the document as a Python
literal. Use it for each key, path and enum member.
Three name faults are the generator's to prevent. The language package
changes one name at a time and cannot see them:
- **Two names of the document that give one Python name.** `user-id` and
`user_id` both give `user_id`. The producer that holds a list of names
(the fields of a class, the parameters of a function) makes them
unique.
- **A name that is also a type in the same class.** With
`from __future__ import annotations`, an annotation is read in the
class's own names first. In `date: date | None = None` the annotation
`date` is then the default, `None`. Give a field or a parameter that
is named as a type you write (`date`, `datetime`, `object`, `list`,
`dict`, `str`, `int`, `float`, `bool`) another name and the key as
alias.
- **A name that the base class has.** A field named `schema` replaces
pydantic's method. A member named `request` replaces the method that
every generated method calls.
`PyFile` stops the run for two faults that Python would accept: a path
that cannot be imported, and one name that a file binds twice (two
imports, or an import and a definition).
## 9. A declaration and a type position differ
An object with properties is a class where it is declared, and only a
name where a type is written. The router contract has no argument for
the position. `gen-pydantic` solves this as follows:
- `toPydanticValue(position)` returns the router for a position.
`toPydanticType` is the router for a type. The projection uses the
router for a declaration.
- In a type position, an inline object declares a class beside the
definition that uses it and renders its name. The name comes from the
schema's `stackTrail`: `toInlineClassName` of this package gives it,
and each generator that names the same inline schema gets the same
name.
- Two schemas can give one name: the keys `ship_to` and `shipTo` both
give `ShipTo`. So look for the class with `findInlineClass`, not with
`context.findDefinition`, which compares the name and the file only:
```ts fragment
findInlineClass(context, { name, stackTrail: objectSchema.stackTrail, destinationPath }) ??
this.defineAndRegister({ identifier: createClass(name), value: model, destinationPath })
```
A second walk of one schema gets the class of the first. A name that
is the class of another schema fails the run, and the run writes no
file. The message names both schemas. Make the value of the class with
`stackTrail: objectSchema.stackTrail`: that is how the function
knows the schema of a class.
- `toIdentifierType` gives the kind of the definition. The lint rule
`skmtc/single-dispatch` allows a test of `schema.type` there.
- A generator that writes annotations of its own (the parameters of a
method) calls the exported `toPydanticType`. It does not call
`insertNormalizedModel`, which gives a type alias of the inline class.
## 10. Pitfalls
| Symptom | Fix |
|---|---|
| `cannot be a Python module: 'pet.generated' …` | Set `settings.generatedSuffix` to `""` |
| `has two schemas for the class 'OrderShipTo'` | Two inline schemas give one class name (section 9). Move one to `components.schemas` under its own name, in the document or with an overlay. Or change the name in a clone of the generator |
| `binds the name 'Field' twice` | A model has the name of a library import. Import the library name with an alias (`{ name: 'Field', alias: '_Field' }`) |
| `The import of '@/…' … has no names` | An import of a project file names what it takes: `{ '@/pkg/_client.py': ['Client'] }` |
| `TypeError: Unable to evaluate type annotation 'date \| None'` | A field has the name of its own type (section 8) |
| `ImportError: cannot import name … (most likely due to a circular import)` | Register a deferred import for a reference inside a cycle (section 3) |
| `IndentationError` in the output | A template wrote leading spaces. Put the part in a `PyBody` |
| A class of an Index renders `pass` | The body got a copy of `definitions`. Give it the array itself |
| `SyntaxError` at a bare `*` | Build the list with `PyParameters` |
| `Registered definition mismatch` on a member that many operations share | That member is not an operation projection. Use an accumulator (`ClientClass` in `gen-httpx-pydantic`) |
| pydantic fails at import on `Field(discriminator=…)` | Render a plain union. A document does not promise a `Literal` discriminator on each member |