-
Notifications
You must be signed in to change notification settings - Fork 228
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
Closed
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
7cf76c0
union implementation
GrantRheingold 65a4274
progress on union
GrantRheingold 8c1ce65
updated union logic
GrantRheingold de3328b
update union
GrantRheingold 4c08e41
update imports
GrantRheingold 1ba3deb
remove unused import
GrantRheingold File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
95 changes: 95 additions & 0 deletions
95
generators/python-v2/pydantic-model/src/v2/UnionGenerator.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] })); | ||
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; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
18 changes: 18 additions & 0 deletions
18
seed/pydantic-v2/exhaustive/resources/types/resources/union/types/animal.py
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
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 theUnion
import:This will ensure the generated Python code has all necessary imports for the discriminated union implementation.
Spotted by Diamond
Is this helpful? React 👍 or 👎 to let us know.