Skip to content

Commit 8736216

Browse files
authored
Merge pull request #145 from ImogenBits/ref_annotations
move ref annotation validation into pydantic schema
2 parents 8177971 + 507210b commit 8736216

1 file changed

Lines changed: 21 additions & 14 deletions

File tree

algobattle/problem.py

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,13 @@
2828
GetCoreSchemaHandler,
2929
ValidationInfo,
3030
)
31+
from pydantic.main import BaseModel
3132
from pydantic_core import CoreSchema
32-
from pydantic_core.core_schema import with_info_after_validator_function
33+
from pydantic_core.core_schema import (
34+
with_info_after_validator_function,
35+
with_info_wrap_validator_function,
36+
ValidatorFunctionWrapHandler,
37+
)
3338

3439
from algobattle.util import (
3540
EncodableModel,
@@ -503,20 +508,22 @@ class InstanceSolutionModel(EncodableModel):
503508
"""Base class for Instance and solution models."""
504509

505510
@classmethod
506-
def model_validate( # noqa: D102
507-
cls,
508-
obj: Any,
509-
*,
510-
strict: bool | None = None,
511-
from_attributes: bool | None = None,
512-
context: dict[str, Any] | None = None,
513-
) -> Self:
514-
model = super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)
515-
model_type = "instance" if issubclass(cls, InstanceModel) else "solution"
511+
def __get_pydantic_core_schema__(cls, source: type[BaseModel], handler: GetCoreSchemaHandler) -> CoreSchema:
512+
schema = handler(cls)
513+
try:
514+
model_type = "instance" if issubclass(cls, InstanceModel) else "solution"
515+
except NameError:
516+
return schema
516517
if cls._validate_with_self(model_type):
517-
context = (context or {}) | {"self": model, model_type: model}
518-
model = super().model_validate(obj, context=context)
519-
return model
518+
519+
def validate_with_self(input: object, validate: ValidatorFunctionWrapHandler, info: ValidationInfo) -> Self:
520+
self = validate(input)
521+
if info.context is None or "self" not in info.context:
522+
self = cls.model_validate(input, context=(info.context or {}) | {"self": self, model_type: self})
523+
return self
524+
525+
schema = with_info_wrap_validator_function(validate_with_self, schema)
526+
return schema
520527

521528
@classmethod
522529
def _annotation_needs_self(cls, annotation: object, model_type: ModelType) -> bool:

0 commit comments

Comments
 (0)