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

Passing data to default_factory in with_default_schema #1582

Open
RolandSaur opened this issue Dec 16, 2024 · 0 comments
Open

Passing data to default_factory in with_default_schema #1582

RolandSaur opened this issue Dec 16, 2024 · 0 comments

Comments

@RolandSaur
Copy link

I am trying to replace a model with a default model in case validation fails. But I would like to customize the default model based on the error message.

For this I am using with_default_schema and am trying to pass data to default_factory.

My Question: How to pass the validation error to the default_factory of with_default_schema?

Minimal Example:
The Minimal Example validates an Item and calls error_handler because of a validation error. This part works. However from the docs it is not clear how to pass anything to the error_handler. context is simply None.

from pydantic import BaseModel, Field, model_validator
from pydantic_core import SchemaValidator, core_schema
from typing import Any

class Item(BaseModel):
    value: float = Field(ge=0)
    weight: float = Field(ge=0)


def error_handler(context: dict[str, Any]) -> Item:
    return Item(value=0, weight=0)

default_item_schema = core_schema.with_default_schema(
    schema=Item.__pydantic_core_schema__,
    default_factory=error_handler,
    default_factory_takes_data=True,
    on_error="default",
)
item_validator = SchemaValidator(default_item_schema)

default_item = item_validator.validate_python({"value": -5, "weight": 4})

System:

  • pydantic version 2.10.3
  • python version 3.12.3
  • OS: Kubuntu 24.04
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