Coverage for bioimageio/spec/_internal/node.py: 100%

20 statements  

« prev     ^ index     » next       coverage.py v7.9.1, created at 2025-06-27 09:20 +0000

1from __future__ import annotations 

2 

3import collections.abc 

4from typing import ( 

5 Any, 

6 Mapping, 

7 Optional, 

8 Type, 

9 Union, 

10) 

11 

12import pydantic 

13from typing_extensions import Self 

14 

15from .type_guards import is_kwargs 

16from .validation_context import ValidationContext, get_validation_context 

17 

18 

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

20 return ( 

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

22 if hasattr(node, "implemented_type") 

23 and hasattr(node, "implemented_format_version") 

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

25 ) 

26 

27 

28class Node( 

29 pydantic.BaseModel, 

30 extra="forbid", 

31 frozen=False, 

32 populate_by_name=True, 

33 revalidate_instances="never", 

34 validate_assignment=True, 

35 validate_default=False, 

36 validate_return=True, # TODO: check if False here would bring a speedup and can still be safe 

37 use_attribute_docstrings=True, 

38 model_title_generator=_node_title_generator, 

39): 

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

41 

42 @classmethod 

43 def model_validate( 

44 cls, 

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

46 *, 

47 strict: Optional[bool] = None, 

48 from_attributes: Optional[bool] = None, 

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

50 by_alias: bool | None = None, 

51 by_name: bool | None = None, 

52 ) -> Self: 

53 """Validate a pydantic model instance. 

54 

55 Args: 

56 obj: The object to validate. 

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

58 from_attributes: Whether to extract data from object attributes. 

59 context: Additional context to pass to the validator. 

60 

61 Raises: 

62 ValidationError: If the object failed validation. 

63 

64 Returns: 

65 The validated description instance. 

66 """ 

67 __tracebackhide__ = True 

68 

69 if context is None: 

70 context = get_validation_context() 

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

72 context = ValidationContext(**context) 

73 

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

75 

76 with context: 

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

78 return super().model_validate( 

79 obj, strict=strict, from_attributes=from_attributes 

80 )