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

Fix generic computed fields #6988

Merged
merged 2 commits into from Aug 16, 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
1 change: 1 addition & 0 deletions pydantic/_internal/_generate_schema.py
Expand Up @@ -1427,6 +1427,7 @@ def _computed_field_schema(
code='model-field-missing-annotation',
)

return_type = replace_types(return_type, self._typevars_map)
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
26 changes: 25 additions & 1 deletion tests/test_computed_fields.py
@@ -1,7 +1,7 @@
import random
import sys
from abc import ABC, abstractmethod
from typing import Any, Callable, ClassVar, List, Tuple
from typing import Any, Callable, ClassVar, Generic, List, Tuple, TypeVar

import pytest
from pydantic_core import ValidationError, core_schema
Expand Down Expand Up @@ -717,3 +717,27 @@ def test_multiple_references_to_schema(model_factory: Callable[[], Any]) -> None
'title': 'Model',
'type': 'object',
}


def test_generic_computed_field():
T = TypeVar('T')

class A(BaseModel, Generic[T]):
x: T

@computed_field
@property
def double_x(self) -> T:
return self.x * 2

assert A[int](x=1).model_dump() == {'x': 1, 'double_x': 2}
assert A[str](x='abc').model_dump() == {'x': 'abc', 'double_x': 'abcabc'}

class B(BaseModel, Generic[T]):
@computed_field
@property
def double_x(self) -> T:
return 'abc' # this may not match the annotated return type, and will warn if not

with pytest.warns(UserWarning, match='Expected `int` but got `str` - serialized value may not be as expected'):
B[int]().model_dump()