Coverage for src/bioimageio/spec/_internal/validated_string.py: 100%
27 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-18 09:17 +0000
« prev ^ index » next coverage.py v7.15.4, created at 2026-08-18 09:17 +0000
1from __future__ import annotations
3from typing import Any, ClassVar
5from pydantic import GetCoreSchemaHandler, GetJsonSchemaHandler, RootModel
6from pydantic.json_schema import JsonSchemaValue
7from pydantic_core.core_schema import (
8 CoreSchema,
9 no_info_after_validator_function,
10)
11from typing_extensions import Self
14class ValidatedString(str):
15 root_model: ClassVar[type[RootModel[Any]]] = RootModel[str]
16 """the pydantic root model to validate the string"""
17 # TODO: should we use a TypeAdapter instead?
18 # TODO: with future py version: RootModel[Any] -> RootModel[str | "literal string type"]
19 _validated: Any # initalized in __new__
21 def __new__(cls, object: object):
22 _validated = cls.root_model.model_validate(object).root
23 self = super().__new__(cls, _validated)
24 self._validated = _validated
25 return self._after_validator()
27 def _after_validator(self) -> Self:
28 """add validation after the `root_model`"""
29 return self
31 @classmethod
32 def __get_pydantic_core_schema__(
33 cls, source_type: Any, handler: GetCoreSchemaHandler
34 ) -> CoreSchema:
35 return no_info_after_validator_function(cls, handler(str))
37 @classmethod
38 def __get_pydantic_json_schema__(
39 cls, core_schema: CoreSchema, handler: GetJsonSchemaHandler
40 ) -> JsonSchemaValue:
41 json_schema = cls.root_model.model_json_schema(mode=handler.mode)
42 json_schema["title"] = cls.__name__.strip("_")
43 if cls.__doc__:
44 json_schema["description"] = cls.__doc__
46 return json_schema