-
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
Closed
aryehklein
wants to merge
4
commits into
fern-api:main
from
aryehklein:feature/fern/support-annotated
Closed
Changes from 3 commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
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
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
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
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
164 changes: 164 additions & 0 deletions
164
generators/python/tests/pydantic_model/test_annotated_field_aliases.py
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,164 @@ | ||
| 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 |
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
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.
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