Skip to content

feat(typescript) [DRAFT] Add support for discriminated unions in Python v2 generator #7553

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
95 changes: 95 additions & 0 deletions generators/python-v2/pydantic-model/src/v2/UnionGenerator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { RelativeFilePath } from "@fern-api/fs-utils";
import { python } from "@fern-api/python-ast";
import { WriteablePythonFile } from "@fern-api/python-base";

import { SingleUnionType, TypeDeclaration, TypeId, UnionTypeDeclaration } from "@fern-fern/ir-sdk/api";

import { PydanticModelGeneratorContext } from "../ModelGeneratorContext";

export class UnionGenerator {
constructor(
private readonly typeId: TypeId,
private readonly context: PydanticModelGeneratorContext,
private readonly typeDeclaration: TypeDeclaration,
private readonly unionDeclaration: UnionTypeDeclaration
) {}

public doGenerate(): WriteablePythonFile {
const path = this.context.getModulePathForId(this.typeId);
const filename = this.context.getSnakeCaseSafeName(this.typeDeclaration.name.name);
const file = python.file({ path });

// Add imports
file.addReference(python.reference({ name: "Union", modulePath: ["typing"] }));
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The code adds a field with a Literal type but is missing the required import. Please add the following import after the Union import:

file.addReference(python.reference({ name: "Literal", modulePath: ["typing"] }));

This will ensure the generated Python code has all necessary imports for the discriminated union implementation.

Suggested change
file.addReference(python.reference({ name: "Union", modulePath: ["typing"] }));
file.addReference(python.reference({ name: "Union", modulePath: ["typing"] }));
file.addReference(python.reference({ name: "Literal", modulePath: ["typing"] }));

Spotted by Diamond

Is this helpful? React 👍 or 👎 to let us know.

file.addReference(python.reference({ name: "Literal", modulePath: ["typing"] }));

// Generate variant classes
this.unionDeclaration.types.forEach((variant: SingleUnionType) => {
file.addReference(
python.reference({
name: `${this.context.getPascalCaseSafeName(variant.discriminantValue.name)}`,
modulePath: [`.${this.context.getPascalCaseSafeName(variant.discriminantValue.name).toLowerCase()}`]
})
);
const variantClass = python.class_({
name: `${this.context.getPascalCaseSafeName(this.typeDeclaration.name.name)}_${this.context.getPascalCaseSafeName(variant.discriminantValue.name)}(${this.context.getPascalCaseSafeName(variant.discriminantValue.name)})`,
extends_: [
...this.unionDeclaration.extends.map((type) =>
this.context.pythonTypeMapper.convertToClassReference(type)
)
]
});

// Add the literal type field
variantClass.add(
python.field({
name: this.context.getSnakeCaseSafeName(this.typeDeclaration.name.name),
type: python.Type.literal(
`${this.context.getPascalCaseSafeName(variant.discriminantValue.name).toLowerCase()}`
)
})
);

variantClass.add(this.getConfigClass());

file.addStatement(variantClass);
});

// Add union type
file.addStatement(
python.codeBlock((writer) => {
writer.write(`${this.context.getPascalCaseSafeName(this.typeDeclaration.name.name)} = Union[`);
this.unionDeclaration.types.forEach((variant, index) => {
if (index > 0) {
writer.write(", ");
}
writer.write(
`${this.context.getPascalCaseSafeName(this.typeDeclaration.name.name)}_${this.context.getPascalCaseSafeName(variant.discriminantValue.name)}`
);
});
writer.write("]");
})
);

return new WriteablePythonFile({
contents: file,
directory: RelativeFilePath.of(path.join("/")),
filename
});
}

private getConfigClass(): python.Class {
const configClass = python.class_({
name: "Config"
});

configClass.addField(
python.field({
name: "allow_population_by_field_name",
initializer: python.TypeInstantiation.bool(true)
})
);

return configClass;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { WriteablePythonFile } from "@fern-api/python-base";

import { PydanticModelGeneratorContext } from "../ModelGeneratorContext";
import { ObjectGenerator } from "./ObjectGenerator";
import { UnionGenerator } from "./UnionGenerator";
import { WrappedAliasGenerator } from "./WrappedAliasGenerator";

export function generateV2Models({ context }: { context: PydanticModelGeneratorContext }): WriteablePythonFile[] {
Expand All @@ -16,7 +17,9 @@ export function generateV2Models({ context }: { context: PydanticModelGeneratorC
return new ObjectGenerator(typeId, context, typeDeclaration, objectTypDeclaration).doGenerate();
},
undiscriminatedUnion: () => undefined,
union: () => undefined,
union: (unionTypeDeclaration) => {
return new UnionGenerator(typeId, context, typeDeclaration, unionTypeDeclaration).doGenerate();
},
_other: () => undefined
});
if (file != null) {
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading