Skip to content
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

Save return type generated from type annotation in ComputedFieldInfo #7889

Merged
merged 1 commit into from Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions pydantic/_internal/_generate_schema.py
Expand Up @@ -1509,6 +1509,9 @@ def _computed_field_schema(
)

return_type = replace_types(return_type, self._typevars_map)
# Create a new ComputedFieldInfo so that different type parametrizations of the same
# generic model's computed field can have different return types.
d.info = dataclasses.replace(d.info, return_type=return_type)
return_type_schema = self.generate_schema(return_type)
# Apply serializers to computed field if there exist
return_type_schema = self._apply_field_serializers(
Expand Down
4 changes: 4 additions & 0 deletions tests/test_computed_fields.py
Expand Up @@ -736,6 +736,10 @@ def double_x(self) -> T:
assert A[int](x=1).model_dump() == {'x': 1, 'double_x': 2}
assert A[str](x='abc').model_dump() == {'x': 'abc', 'double_x': 'abcabc'}

assert A(x='xxxxxx').model_computed_fields['double_x'].return_type == T
assert A[int](x=123).model_computed_fields['double_x'].return_type == int
assert A[str](x='x').model_computed_fields['double_x'].return_type == str

class B(BaseModel, Generic[T]):
@computed_field
@property
Expand Down