-
Notifications
You must be signed in to change notification settings - Fork 268
[feature] Support generating pydantic types with Annotated attributes #9445
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
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -35,6 +35,7 @@ def __init__( | |
| update_forward_ref_function_reference: AST.Reference, | ||
| field_metadata_getter: Callable[[], FieldMetadata], | ||
| use_pydantic_field_aliases: bool, | ||
| use_annotated_field_aliases: bool, | ||
| should_export: bool = True, | ||
| base_models: Sequence[AST.ClassReference] = [], | ||
| parent: Optional[ClassParent] = None, | ||
|
|
@@ -78,6 +79,7 @@ def __init__( | |
| self._update_forward_ref_function_reference = update_forward_ref_function_reference | ||
| self._field_metadata_getter = field_metadata_getter | ||
| self._use_pydantic_field_aliases = use_pydantic_field_aliases | ||
| self._use_annotated_field_aliases = use_annotated_field_aliases | ||
|
|
||
| def to_reference(self) -> LocalClassReference: | ||
| return self._local_class_reference | ||
|
|
@@ -125,7 +127,39 @@ def add_field(self, unsanitized_field: PydanticField) -> None: | |
| version=self._version, | ||
| ) | ||
|
|
||
| if is_aliased and not self._use_pydantic_field_aliases: | ||
| # Handle field aliasing approaches (mutually exclusive) | ||
| if ( | ||
| is_aliased | ||
| and self._use_annotated_field_aliases | ||
| and self._version == PydanticVersionCompatibility.V2 | ||
| ): | ||
| # New annotated field aliases feature - use pydantic.Field in Annotated | ||
| pydantic_field_annotation = AST.Expression( | ||
| AST.FunctionInvocation( | ||
| function_definition=Pydantic(self._version).Field(), | ||
| kwargs=[("alias", AST.Expression(f'"{field.json_field_name}"'))] | ||
| ) | ||
| ) | ||
|
|
||
| # Create annotated type hint | ||
| annotated_type_hint = AST.TypeHint.annotated( | ||
| type=field.type_hint, | ||
| annotation=pydantic_field_annotation, | ||
| ) | ||
|
|
||
| # Update field with new type hint | ||
| prev_fields = field.__dict__ | ||
| del prev_fields["type_hint"] | ||
| field = PydanticField( | ||
| **(field.__dict__), | ||
| type_hint=annotated_type_hint, | ||
| ) | ||
|
|
||
| # Use only the default value as initializer, not pydantic.Field | ||
| initializer = default_value | ||
|
|
||
| elif is_aliased and not self._use_pydantic_field_aliases: | ||
|
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. There is a bit of complexity here with how this new feature interplays with use_pydantic_field_aliases. If use_pydantic_field_aliases is false, and _use_annotated_field_aliases is true, you get into double annotated types. The FastAPI generator defaults this to true, whereas the use_pydantic_field_aliases defaults to false. I think this if/elif block handles it, but lmk if there are other edge cases to consider!
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As far as I know this is reasonable! I'm good with the approach of just preferring it over the other flag (rather than e.g. breaking the config shape), as long as we document that that's the behavior. |
||
| # Legacy approach - use FieldMetadata in Annotated | ||
| field_metadata = self._field_metadata_getter().get_instance() | ||
| field_metadata.add_alias(field.json_field_name) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,217 @@ | ||
| import textwrap | ||
| from fern_python.codegen import AST | ||
| from fern_python.external_dependencies import PydanticVersionCompatibility | ||
| from fern_python.generators.pydantic_model.field_metadata import FieldMetadata | ||
| from fern_python.pydantic_codegen import PydanticField, PydanticModel | ||
| from fern_python.source_file_factory import SourceFileFactory | ||
|
|
||
|
|
||
| def test_annotated_field_aliases_generation() -> None: | ||
| """Test that use_annotated_field_aliases generates the correct annotated type syntax""" | ||
| source_file = SourceFileFactory(should_format=True).create_snippet() | ||
|
|
||
| # Mock field metadata getter | ||
| def mock_field_metadata_getter() -> FieldMetadata: | ||
| return FieldMetadata(reference=AST.ClassReference(qualified_name_excluding_import=("FieldMetadata",))) | ||
|
|
||
| # Create PydanticModel with annotated field aliases enabled | ||
| model = PydanticModel( | ||
| source_file=source_file, | ||
| name="TestModel", | ||
| frozen=False, | ||
| orm_mode=False, | ||
| smart_union=False, | ||
| version=PydanticVersionCompatibility.V2, | ||
| is_pydantic_v2=AST.Expression("True"), | ||
| universal_root_validator=lambda pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("validator",)) | ||
| ), | ||
| universal_field_validator=lambda field_name, pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("field_validator",)) | ||
| ), | ||
| require_optional_fields=False, | ||
| update_forward_ref_function_reference=AST.Reference(qualified_name_excluding_import=("update_refs",)), | ||
| field_metadata_getter=mock_field_metadata_getter, | ||
| use_pydantic_field_aliases=True, # This should be ignored when use_annotated_field_aliases=True | ||
| use_annotated_field_aliases=True, # Enable the new feature | ||
| ) | ||
|
|
||
| # Add a field with an alias | ||
| field = PydanticField( | ||
| name="total_items", | ||
| pascal_case_field_name="TotalItems", | ||
| json_field_name="totalItems", | ||
| type_hint=AST.TypeHint.int_(), | ||
| description="Total number of items", | ||
| ) | ||
| model.add_field(field) | ||
|
|
||
| model.finish() | ||
|
|
||
| # Generate the code | ||
| generated_code = source_file.to_str() | ||
|
|
||
| # Verify the generated code contains the annotated syntax | ||
| assert "import typing_extensions" in generated_code | ||
| assert "import pydantic" in generated_code | ||
| assert "typing_extensions.Annotated" in generated_code | ||
| assert 'pydantic.Field(\n alias="totalItems"' in generated_code | ||
|
|
||
| # Verify it does NOT contain the old syntax | ||
| assert "total_items: int = pydantic.Field(" not in generated_code | ||
|
|
||
|
|
||
| def test_annotated_field_aliases_disabled() -> None: | ||
| """Test that when disabled, it uses the traditional pydantic.Field syntax""" | ||
| source_file = SourceFileFactory(should_format=True).create_snippet() | ||
|
|
||
| # Mock field metadata getter | ||
| def mock_field_metadata_getter() -> FieldMetadata: | ||
| return FieldMetadata(reference=AST.ClassReference(qualified_name_excluding_import=("FieldMetadata",))) | ||
|
|
||
| # Create PydanticModel with annotated field aliases disabled (default) | ||
| model = PydanticModel( | ||
| source_file=source_file, | ||
| name="TestModel", | ||
| frozen=False, | ||
| orm_mode=False, | ||
| smart_union=False, | ||
| version=PydanticVersionCompatibility.V2, | ||
| is_pydantic_v2=AST.Expression("True"), | ||
| universal_root_validator=lambda pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("validator",)) | ||
| ), | ||
| universal_field_validator=lambda field_name, pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("field_validator",)) | ||
| ), | ||
| require_optional_fields=False, | ||
| update_forward_ref_function_reference=AST.Reference(qualified_name_excluding_import=("update_refs",)), | ||
| field_metadata_getter=mock_field_metadata_getter, | ||
| use_pydantic_field_aliases=True, # Traditional behavior | ||
| use_annotated_field_aliases=False, # Disabled | ||
| ) | ||
|
|
||
| # Add a field with an alias | ||
| field = PydanticField( | ||
| name="total_items", | ||
| pascal_case_field_name="TotalItems", | ||
| json_field_name="totalItems", | ||
| type_hint=AST.TypeHint.int_(), | ||
| description="Total number of items", | ||
| ) | ||
| model.add_field(field) | ||
|
|
||
| model.finish() | ||
|
|
||
| # Generate the code | ||
| generated_code = source_file.to_str() | ||
|
|
||
| # Verify the generated code uses traditional syntax | ||
| assert "total_items: int = pydantic.Field(alias=\"totalItems\"" in generated_code | ||
|
|
||
| # Verify it does NOT contain the annotated syntax | ||
| assert "typing.Annotated[int, pydantic.Field(" not in generated_code | ||
|
|
||
|
|
||
| def test_annotated_field_aliases_only_v2() -> None: | ||
| """Test that annotated field aliases only work with Pydantic v2""" | ||
| source_file = SourceFileFactory(should_format=True).create_snippet() | ||
|
|
||
| # Mock field metadata getter | ||
| def mock_field_metadata_getter() -> FieldMetadata: | ||
| return FieldMetadata(reference=AST.ClassReference(qualified_name_excluding_import=("FieldMetadata",))) | ||
|
|
||
| # Create PydanticModel with annotated field aliases enabled but v1 | ||
| model = PydanticModel( | ||
| source_file=source_file, | ||
| name="TestModel", | ||
| frozen=False, | ||
| orm_mode=False, | ||
| smart_union=False, | ||
| version=PydanticVersionCompatibility.V1, # v1, not v2 | ||
| is_pydantic_v2=AST.Expression("False"), | ||
| universal_root_validator=lambda pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("validator",)) | ||
| ), | ||
| universal_field_validator=lambda field_name, pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("field_validator",)) | ||
| ), | ||
| require_optional_fields=False, | ||
| update_forward_ref_function_reference=AST.Reference(qualified_name_excluding_import=("update_refs",)), | ||
| field_metadata_getter=mock_field_metadata_getter, | ||
| use_pydantic_field_aliases=True, | ||
| use_annotated_field_aliases=True, # Enabled but should be ignored for v1 | ||
| ) | ||
|
|
||
| # Add a field with an alias | ||
| field = PydanticField( | ||
| name="total_items", | ||
| pascal_case_field_name="TotalItems", | ||
| json_field_name="totalItems", | ||
| type_hint=AST.TypeHint.int_(), | ||
| ) | ||
| model.add_field(field) | ||
|
|
||
| model.finish() | ||
|
|
||
| # Generate the code | ||
| generated_code = source_file.to_str() | ||
|
|
||
| # Should fall back to traditional syntax for v1 | ||
| assert "total_items: int = pydantic.Field(alias=\"totalItems\"" in generated_code | ||
|
|
||
| # Should NOT use annotated syntax for v1 | ||
| assert "typing.Annotated[int, pydantic.Field(" not in generated_code | ||
|
|
||
|
|
||
| def test_no_double_annotation() -> None: | ||
| """Test that we don't get double annotations when use_annotated_field_aliases=True""" | ||
| source_file = SourceFileFactory(should_format=True).create_snippet() | ||
|
|
||
| # Mock field metadata getter | ||
| def mock_field_metadata_getter() -> FieldMetadata: | ||
| return FieldMetadata(reference=AST.ClassReference(qualified_name_excluding_import=("FieldMetadata",))) | ||
|
|
||
| # Create PydanticModel with both flags set - this used to cause double annotation | ||
| model = PydanticModel( | ||
| source_file=source_file, | ||
| name="TestModel", | ||
| frozen=False, | ||
| orm_mode=False, | ||
| smart_union=False, | ||
| version=PydanticVersionCompatibility.V2, | ||
| is_pydantic_v2=AST.Expression("True"), | ||
| universal_root_validator=lambda pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("validator",)) | ||
| ), | ||
| universal_field_validator=lambda field_name, pre: AST.FunctionInvocation( | ||
| function_definition=AST.Reference(qualified_name_excluding_import=("field_validator",)) | ||
| ), | ||
| require_optional_fields=False, | ||
| update_forward_ref_function_reference=AST.Reference(qualified_name_excluding_import=("update_refs",)), | ||
| field_metadata_getter=mock_field_metadata_getter, | ||
| use_pydantic_field_aliases=False, # This would trigger FieldMetadata approach | ||
| use_annotated_field_aliases=True, # This should override and use pydantic.Field approach | ||
| ) | ||
|
|
||
| # Add a field with an alias | ||
| field = PydanticField( | ||
| name="total_items", | ||
| pascal_case_field_name="TotalItems", | ||
| json_field_name="totalItems", | ||
| type_hint=AST.TypeHint.int_(), | ||
| ) | ||
| model.add_field(field) | ||
|
|
||
| model.finish() | ||
|
|
||
| # Generate the code | ||
| generated_code = source_file.to_str() | ||
|
|
||
| # Should only have ONE level of Annotated, not nested | ||
| assert "typing_extensions.Annotated" in generated_code | ||
| assert 'pydantic.Field(\n alias="totalItems"' in generated_code | ||
|
|
||
| # Should NOT have double annotation (FieldMetadata inside pydantic.Field annotation) | ||
| assert "FieldMetadata" not in generated_code | ||
| assert generated_code.count("typing_extensions.Annotated") == 1 |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
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.
High level points:
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.
Great questions!
pnpm seed:local test --generator python-sdk --fixture alias-extends --outputFolder <whatever_you_name_the_output_folder>. This will also run ruff and mypy against the files