Pydantic schema cannot validate self defined types
Opened this issue · 0 comments
denghz commented
Bug Description
Pydantic schema fails to validate user-defined types.
Expected Behavior
The Pydantic schema should successfully validate user-defined types.
Code Example
Below is a minimal code example to illustrate the issue:
from typing import Any
from pydantic import BaseModel, Field
from pydantic_core import CoreSchema, GetCoreSchemaHandler
from typing_extensions import Annotated
PositiveInt = Annotated[int, Field(gt=0)]
class Username(str):
@classmethod
def __get_pydantic_core_schema__(
cls, source_type: Any, handler: GetCoreSchemaHandler
) -> CoreSchema:
return core_schema.no_info_after_validator_function(cls, handler(str))
class Model(BaseModel):
annotated_type: Option[PositiveInt] = Nothing
annotated_type_none: Option[PositiveInt] = Nothing
custom_type: Option[Username] = Nothing
custom_type_none: Option[Username] = Nothing
obj = dict(
annotated_type=20,
annotated_type_none=None,
custom_type='test_user',
custom_type_none=None
)
model = Model.model_validate(obj)
Additional Context
- The
is_instance_schema
function does not work for annotated types. - A potential solution could be to either remove the annotations or avoid checking
is_instance
since the validator of the inner typeT
ofOption[T]
should validate the value itself.
Environment
- Pydantic version: latest