dbrattli / Expression

Pragmatic functional programming for Python inspired by F#
https://expression.readthedocs.io
MIT License
421 stars 30 forks source link

Pydantic schema cannot validate self defined types #206

Open denghz opened 2 weeks ago

denghz commented 2 weeks ago

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

Environment