Coverage for bioimageio/spec/_internal/node.py: 100%
19 statements
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-02 14:21 +0000
« prev ^ index » next coverage.py v7.8.0, created at 2025-04-02 14:21 +0000
1from __future__ import annotations
3from typing import (
4 Any,
5 Dict,
6 Optional,
7 Type,
8 Union,
9)
11import pydantic
12from typing_extensions import Self
14from .type_guards import is_kwargs
15from .validation_context import ValidationContext, get_validation_context
18def _node_title_generator(node: Type[Node]) -> str:
19 return (
20 f"{node.implemented_type} {node.implemented_format_version}" # pyright: ignore[reportAttributeAccessIssue]
21 if hasattr(node, "implemented_type")
22 and hasattr(node, "implemented_format_version")
23 else f"{node.__module__.replace('bioimageio.spec.', '')}.{node.__name__}"
24 )
27class Node(
28 pydantic.BaseModel,
29 extra="forbid",
30 frozen=False,
31 populate_by_name=True,
32 revalidate_instances="never",
33 validate_assignment=True,
34 validate_default=False,
35 validate_return=True, # TODO: check if False here would bring a speedup and can still be safe
36 use_attribute_docstrings=True,
37 model_title_generator=_node_title_generator,
38):
39 """""" # empty docstring to remove all pydantic docstrings from the pdoc spec docs
41 @classmethod
42 def model_validate(
43 cls,
44 obj: Union[Any, Dict[str, Any]],
45 *,
46 strict: Optional[bool] = None,
47 from_attributes: Optional[bool] = None,
48 context: Union[ValidationContext, Dict[str, Any], None] = None,
49 ) -> Self:
50 """Validate a pydantic model instance.
52 Args:
53 obj: The object to validate.
54 strict: Whether to raise an exception on invalid fields.
55 from_attributes: Whether to extract data from object attributes.
56 context: Additional context to pass to the validator.
58 Raises:
59 ValidationError: If the object failed validation.
61 Returns:
62 The validated description instance.
63 """
64 __tracebackhide__ = True
66 if context is None:
67 context = get_validation_context()
68 elif isinstance(context, dict):
69 context = ValidationContext(**context)
71 assert not isinstance(obj, dict) or is_kwargs(obj), obj
73 with context:
74 # use validation context as context manager for equal behavior of __init__ and model_validate
75 return super().model_validate(
76 obj, strict=strict, from_attributes=from_attributes
77 )