(
typeName: string,
schema: JSONSchema7,
ctx: PyCodegenCtx,
description?: string,
experimental = isSchemaExperimental(schema)
)
| 2203 | } |
| 2204 | |
| 2205 | function emitPyClass( |
| 2206 | typeName: string, |
| 2207 | schema: JSONSchema7, |
| 2208 | ctx: PyCodegenCtx, |
| 2209 | description?: string, |
| 2210 | experimental = isSchemaExperimental(schema) |
| 2211 | ): void { |
| 2212 | if (ctx.generatedNames.has(typeName)) { |
| 2213 | return; |
| 2214 | } |
| 2215 | ctx.generatedNames.add(typeName); |
| 2216 | |
| 2217 | const required = new Set(schema.required || []); |
| 2218 | const fieldEntries = Object.entries(schema.properties || {}).filter( |
| 2219 | ([, value]) => typeof value === "object" |
| 2220 | ) as Array<[string, JSONSchema7]>; |
| 2221 | const orderedFieldEntries = [ |
| 2222 | ...fieldEntries.filter(([name]) => required.has(name)).sort(([a], [b]) => a.localeCompare(b)), |
| 2223 | ...fieldEntries.filter(([name]) => !required.has(name)).sort(([a], [b]) => a.localeCompare(b)), |
| 2224 | ]; |
| 2225 | |
| 2226 | const fieldInfos = orderedFieldEntries.map(([propName, propSchema]) => { |
| 2227 | const isRequired = required.has(propName); |
| 2228 | const resolved = resolvePyPropertyType(propSchema, typeName, propName, isRequired, ctx); |
| 2229 | const baseFieldName = toPyFieldName(propName, propSchema, ctx); |
| 2230 | const fieldName = isSchemaInternal(propSchema) ? `_${baseFieldName}` : baseFieldName; |
| 2231 | return { |
| 2232 | jsonName: propName, |
| 2233 | fieldName, |
| 2234 | isRequired, |
| 2235 | resolved, |
| 2236 | }; |
| 2237 | }); |
| 2238 | |
| 2239 | const lines: string[] = []; |
| 2240 | if (experimental) { |
| 2241 | pushPyExperimentalComment(lines, "type"); |
| 2242 | } |
| 2243 | if (isSchemaDeprecated(schema)) { |
| 2244 | lines.push(`# Deprecated: this type is deprecated and will be removed in a future version.`); |
| 2245 | } |
| 2246 | lines.push(`@dataclass`); |
| 2247 | lines.push(`class ${typeName}:`); |
| 2248 | if (description || schema.description) { |
| 2249 | lines.push(` ${pyDocstringLiteral(description || schema.description || "")}`); |
| 2250 | } |
| 2251 | |
| 2252 | if (fieldInfos.length === 0) { |
| 2253 | lines.push(` @staticmethod`); |
| 2254 | lines.push(` def from_dict(obj: Any) -> "${typeName}":`); |
| 2255 | lines.push(` assert isinstance(obj, dict)`); |
| 2256 | lines.push(` return ${typeName}()`); |
| 2257 | lines.push(``); |
| 2258 | lines.push(` def to_dict(self) -> dict:`); |
| 2259 | lines.push(` return {}`); |
| 2260 | ctx.classes.push(lines.join("\n")); |
| 2261 | return; |
| 2262 | } |
no test coverage detected
searching dependent graphs…