Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 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
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,13 @@ class BasePydanticModelCustomConfig(pydantic.BaseModel):

use_pydantic_field_aliases: bool = True

use_annotated_field_aliases: bool = False
Copy link
Contributor Author

Choose a reason for hiding this comment

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

High level points:

  1. If this looks good, I assume I also need a docs change - can you point me to where to make that?
  2. I added unit tests for this change, but didnt know how/where to do an end to end test with a full on generation?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Great questions!

  1. We document the pydantic config in a separate repo specifically for our docs. You can see an analogous feature flag docs PR here: Document lazy_imports (Python SDK) docs#702. We're happy to make that PR though if you'd prefer! You've already been so generous with your time on this contribution.
  2. Our strategy for most ETE testing these days uses our framework called seed, which is a regression testing framework that you can read more about in CONTRIBUTING.md.
    • For testing this, I'd probably recommend adding a new alias-extends fixture (could also use exhaustive) with this custom config set
    • You'd then generate and check in the seed files 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
    • If you want more test coverage against the SDK, you can check in additional test files to the generated directory and .fernignore them

"""
When enabled, generates type-safe field aliases using typing.Annotated[Type, pydantic.Field(alias="...")]
instead of field assignments. This improves type checking compatibility with pyright.
Only available for Pydantic v2.
"""

@pydantic.model_validator(mode="after")
def check_wrapped_aliases_v1_or_v2_only(self) -> Self:
version_compat = self.version
Expand All @@ -69,6 +76,11 @@ def check_wrapped_aliases_v1_or_v2_only(self) -> Self:
else:
self.use_str_enums = True

if self.use_annotated_field_aliases and version_compat != PydanticVersionCompatibility.V2:
raise ValueError(
"use_annotated_field_aliases is only supported with Pydantic v2, please set version to 'v2' to use this feature."
)

return self


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ def __init__(
update_forward_ref_function_reference=self._context.core_utilities.get_update_forward_refs(),
field_metadata_getter=lambda: self._context.core_utilities.get_field_metadata(),
use_pydantic_field_aliases=self._custom_config.use_pydantic_field_aliases,
use_annotated_field_aliases=self._custom_config.use_annotated_field_aliases,
)

self._force_update_forward_refs = force_update_forward_refs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -141,6 +143,37 @@ def add_field(self, unsanitized_field: PydanticField) -> None:
type_hint=aliased_type_hint,
)

# New annotated field aliases feature
if (
is_aliased
and self._use_annotated_field_aliases
and self._version == PydanticVersionCompatibility.V2
):
# Create pydantic.Field annotation
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

self._class_declaration.add_class_var(
AST.VariableDeclaration(name=field.name, type_hint=field.type_hint, initializer=initializer)
)
Expand Down
164 changes: 164 additions & 0 deletions generators/python/tests/pydantic_model/test_annotated_field_aliases.py
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
52 changes: 52 additions & 0 deletions generators/python/tests/sdk/test_custom_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,55 @@ def test_parse_wrapped_aliases() -> None:
match="Wrapped aliases are only supported in Pydantic V1, V1_ON_V2, or V2, please update your `version` field appropriately to continue using wrapped aliases.",
):
SDKCustomConfig.parse_obj(both)


def test_annotated_field_aliases() -> None:
# Test that annotated field aliases work with v2
v2_config = {
"pydantic_config": {
"version": "v2",
"use_annotated_field_aliases": True,
},
}
sdk_custom_config = SDKCustomConfig.parse_obj(v2_config)
assert (
sdk_custom_config.pydantic_config.version == "v2"
and sdk_custom_config.pydantic_config.use_annotated_field_aliases is True
)

# Test that annotated field aliases fail with non-v2 versions
v1_config = {
"pydantic_config": {
"version": "v1",
"use_annotated_field_aliases": True,
},
}
with pytest.raises(
pydantic.ValidationError,
match="use_annotated_field_aliases is only supported with Pydantic v2, please set version to 'v2' to use this feature.",
):
SDKCustomConfig.parse_obj(v1_config)

both_config = {
"pydantic_config": {
"version": "both",
"use_annotated_field_aliases": True,
},
}
with pytest.raises(
pydantic.ValidationError,
match="use_annotated_field_aliases is only supported with Pydantic v2, please set version to 'v2' to use this feature.",
):
SDKCustomConfig.parse_obj(both_config)

v1_on_v2_config = {
"pydantic_config": {
"version": "v1_on_v2",
"use_annotated_field_aliases": True,
},
}
with pytest.raises(
pydantic.ValidationError,
match="use_annotated_field_aliases is only supported with Pydantic v2, please set version to 'v2' to use this feature.",
):
SDKCustomConfig.parse_obj(v1_on_v2_config)
Loading