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

Pydantic schema cannot validate self defined types #206

Open
denghz opened this issue Jun 19, 2024 · 0 comments
Open

Pydantic schema cannot validate self defined types #206

denghz opened this issue Jun 19, 2024 · 0 comments

Comments

@denghz
Copy link
Contributor

denghz commented Jun 19, 2024

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 type T of Option[T] should validate the value itself.

Environment

  • Pydantic version: latest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant