Skip to content

Commit

Permalink
Save return type generated from type annotation in ComputedFieldInfo (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
alexmojaki committed Oct 25, 2023
1 parent 93e4d23 commit 18c3880
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
3 changes: 3 additions & 0 deletions pydantic/_internal/_generate_schema.py
Expand Up @@ -1515,6 +1515,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

0 comments on commit 18c3880

Please sign in to comment.