feat(python): add is_* and as_* casting methods for discriminated unions #10769
+161
−0
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.
Description
Refs https://buildwithfern.slack.com/archives/C09NRQZ4A2X/p1763684501766159
Adds type-safe casting methods for discriminated union types in the Python SDK generator, matching the pattern used in the PHP generator. For each union variant, the generator now creates:
is_*()methods to check if the union is of a specific variant typeas_*()methods to cast to the specific type with runtime validationChanges Made
_add_is_method()to generate boolean type-checking methods for each union variant_add_as_method()to generate typed casting methods with runtime validationadd_statements_v1_v2_or_bothpatterngenerators/python/sdk/versions.ymldiscriminated_union_with_utils_generator.pyfor all discriminated union typesExample Generated Code:
Testing
Review Focus Areas
Critical Items:
writer.write_node()for AST.Expression objects. Verify this pattern is correct and doesn't cause syntax errors in edge cases.self.__root__(v1) andself.root(v2) paths work correctly in the generated code.as_*()methods reconstruct typed objects usingdict(exclude_unset=True, exclude={discriminant}). Verify this correctly handles all union variant shapes (same_properties_as_object, single_property, no_properties).as_*()returnsNone. Confirm this is the expected behavior.Implementation Notes:
visit()method in the generation flowDevin Session: https://app.devin.ai/sessions/57d48c907d15446caf2c77e9700bb45d
Requested by: [email protected] (@aditya-arolkar-swe)