|
28 | 28 | GetCoreSchemaHandler, |
29 | 29 | ValidationInfo, |
30 | 30 | ) |
| 31 | +from pydantic.main import BaseModel |
31 | 32 | 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 | +) |
33 | 38 |
|
34 | 39 | from algobattle.util import ( |
35 | 40 | EncodableModel, |
@@ -503,20 +508,22 @@ class InstanceSolutionModel(EncodableModel): |
503 | 508 | """Base class for Instance and solution models.""" |
504 | 509 |
|
505 | 510 | @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 |
516 | 517 | 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 |
520 | 527 |
|
521 | 528 | @classmethod |
522 | 529 | def _annotation_needs_self(cls, annotation: object, model_type: ModelType) -> bool: |
|
0 commit comments