Coverage for src / bioimageio / spec / _internal / node.py: 96%

23 statements  

« prev     ^ index     » next       coverage.py v7.13.1, created at 2026-01-09 13:16 +0000

1from __future__ import annotations 

2 

3import collections.abc 

4import warnings 

5from typing import ( 

6 Any, 

7 Literal, 

8 Mapping, 

9 Optional, 

10 Type, 

11 Union, 

12) 

13 

14import pydantic 

15from typing_extensions import Self 

16 

17from .type_guards import is_kwargs 

18from .validation_context import ValidationContext, get_validation_context 

19 

20 

21def _node_title_generator(node: Type[Node]) -> str: 

22 return ( 

23 f"{node.implemented_type} {node.implemented_format_version}" # pyright: ignore[reportAttributeAccessIssue] 

24 if hasattr(node, "implemented_type") 

25 and hasattr(node, "implemented_format_version") 

26 else f"{node.__module__.replace('bioimageio.spec.', '')}.{node.__name__}" 

27 ) 

28 

29 

30class Node( 

31 pydantic.BaseModel, 

32 allow_inf_nan=False, 

33 extra="forbid", 

34 frozen=False, 

35 model_title_generator=_node_title_generator, 

36 populate_by_name=True, 

37 revalidate_instances="always", 

38 use_attribute_docstrings=True, 

39 validate_assignment=True, 

40 validate_default=True, 

41 validate_return=True, 

42): 

43 """""" # empty docstring to remove all pydantic docstrings from the pdoc spec docs 

44 

45 @classmethod 

46 def model_validate( 

47 cls, 

48 obj: Union[Any, Mapping[str, Any]], 

49 *, 

50 strict: Optional[bool] = None, 

51 extra: Optional[Literal["allow", "ignore", "forbid"]] = None, 

52 from_attributes: Optional[bool] = None, 

53 context: Union[ValidationContext, Mapping[str, Any], None] = None, 

54 by_alias: Optional[bool] = None, 

55 by_name: Optional[bool] = None, 

56 ) -> Self: 

57 """Validate a pydantic model instance. 

58 

59 Args: 

60 obj: The object to validate. 

61 strict: Whether to raise an exception on invalid fields. 

62 from_attributes: Whether to extract data from object attributes. 

63 context: Additional context to pass to the validator. 

64 

65 Raises: 

66 ValidationError: If the object failed validation. 

67 

68 Returns: 

69 The validated description instance. 

70 """ 

71 __tracebackhide__ = True 

72 

73 if context is None: 

74 context = get_validation_context() 

75 elif isinstance(context, collections.abc.Mapping): 

76 context = ValidationContext(**context) 

77 

78 assert not isinstance(obj, collections.abc.Mapping) or is_kwargs(obj), obj 

79 

80 # TODO: pass on extra with pydantic >=2.12 

81 if extra is not None: 

82 warnings.warn("`extra` argument is currently ignored") 

83 

84 with context: 

85 # use validation context as context manager for equal behavior of __init__ and model_validate 

86 return super().model_validate( 

87 obj, strict=strict, from_attributes=from_attributes 

88 )