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

move ref annotation validation into pydantic schema #145

Merged
merged 1 commit into from
Nov 12, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 21 additions & 14 deletions algobattle/problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,13 @@
GetCoreSchemaHandler,
ValidationInfo,
)
from pydantic.main import BaseModel
from pydantic_core import CoreSchema
from pydantic_core.core_schema import with_info_after_validator_function
from pydantic_core.core_schema import (
with_info_after_validator_function,
with_info_wrap_validator_function,
ValidatorFunctionWrapHandler,
)

from algobattle.util import (
EncodableModel,
Expand Down Expand Up @@ -503,20 +508,22 @@ class InstanceSolutionModel(EncodableModel):
"""Base class for Instance and solution models."""

@classmethod
def model_validate( # noqa: D102
cls,
obj: Any,
*,
strict: bool | None = None,
from_attributes: bool | None = None,
context: dict[str, Any] | None = None,
) -> Self:
model = super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)
model_type = "instance" if issubclass(cls, InstanceModel) else "solution"
def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler) -> CoreSchema:
schema = handler(cls)
try:
model_type = "instance" if issubclass(cls, InstanceModel) else "solution"
except NameError:
return schema
if cls._validate_with_self(model_type):
context = (context or {}) | {"self": model, model_type: model}
model = super().model_validate(obj, context=context)
return model

def validate_with_self(input: object, validate: ValidatorFunctionWrapHandler, info: ValidationInfo) -> Self:
self = validate(input)
if info.context is None or "self" not in info.context:
self = cls.model_validate(input, context=(info.context or {}) | {"self": self, model_type: self})
return self

schema = with_info_wrap_validator_function(validate_with_self, schema)
return schema

@classmethod
def _annotation_needs_self(cls, annotation: object, model_type: ModelType) -> bool:
Expand Down
Loading