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

30 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 16:20 +0000

1from __future__ import annotations 

2 

3import collections.abc 

4import warnings 

5from collections.abc import Callable, Mapping 

6from typing import ( 

7 Any, 

8 Literal, 

9) 

10 

11import pydantic 

12from typing_extensions import ParamSpec, Self, TypeVar 

13 

14from .type_guards import is_kwargs, is_mapping 

15from .validation_context import ValidationContext, get_validation_context 

16 

17 

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 ) 

25 

26 

27P = ParamSpec("P") 

28T = TypeVar("T") 

29 

30 

31class Node( 

32 pydantic.BaseModel, 

33 allow_inf_nan=False, 

34 extra="forbid", 

35 frozen=False, 

36 model_title_generator=_node_title_generator, 

37 populate_by_name=True, 

38 revalidate_instances="always", 

39 use_attribute_docstrings=True, 

40 validate_assignment=True, 

41 validate_default=True, 

42 validate_return=True, 

43): 

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

45 """""" # ruff: ignore[D419] 

46 

47 @classmethod 

48 def model_validate( 

49 cls, 

50 obj: Any | Mapping[str, Any], 

51 *, 

52 strict: bool | None = None, 

53 extra: Literal["allow", "ignore", "forbid"] | None = None, 

54 from_attributes: bool | None = None, 

55 context: ValidationContext | Mapping[str, Any] | None = None, 

56 by_alias: bool | None = None, 

57 by_name: bool | None = None, 

58 ) -> Self: 

59 """Validate a pydantic model instance. 

60 

61 Args: 

62 obj: The object to validate. 

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

64 from_attributes: Whether to extract data from object attributes. 

65 context: Additional context to pass to the validator. 

66 

67 Raises: 

68 ValidationError: If the object failed validation. 

69 

70 Returns: 

71 The validated description instance. 

72 """ 

73 __tracebackhide__ = True 

74 

75 if context is None: 

76 context = get_validation_context() 

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

78 context = ValidationContext(**context) 

79 

80 assert not is_mapping(obj) or is_kwargs(obj), obj 

81 

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

83 if extra is not None: 

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

85 

86 with context: 

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

88 return super().model_validate( 

89 obj, strict=strict, from_attributes=from_attributes 

90 ) 

91 

92 @classmethod 

93 def dict_from_kwargs( 

94 cls: Callable[P, T], *args: P.args, **kwargs: P.kwargs 

95 ) -> dict[str, Any]: 

96 assert not args, "Did not expected any args" 

97 return dict(kwargs)