Skip to content
Closed
Show file tree
Hide file tree
Changes from all 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 @@ -195,6 +195,7 @@ def generate(self) -> None:
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,
) as internal_pydantic_model_for_single_union_type:
internal_single_union_type = internal_pydantic_model_for_single_union_type.to_reference()
internal_single_union_types.append(internal_single_union_type)
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 @@ -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:
Copy link
Contributor Author

Choose a reason for hiding this comment

The 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!

Copy link
Collaborator

Choose a reason for hiding this comment

The 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)

Expand Down
217 changes: 217 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,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
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)
25 changes: 25 additions & 0 deletions seed/fastapi/exhaustive/use-annotated-field-aliases/__init__.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading