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

19 statements  

« prev     ^ index     » next       coverage.py v7.6.10, created at 2025-02-05 13:53 +0000

1from __future__ import annotations 

2 

3from typing import ( 

4 Any, 

5 Dict, 

6 Optional, 

7 Type, 

8 Union, 

9) 

10 

11import pydantic 

12from typing_extensions import ( 

13 Self, 

14) 

15 

16from .type_guards import is_kwargs 

17from .validation_context import ValidationContext, validation_context_var 

18 

19 

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

21 return ( 

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

23 if hasattr(node, "implemented_type") 

24 and hasattr(node, "implemented_format_version") 

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

26 ) 

27 

28 

29class Node( 

30 pydantic.BaseModel, 

31 extra="forbid", 

32 frozen=False, 

33 populate_by_name=True, 

34 revalidate_instances="never", 

35 validate_assignment=True, 

36 validate_default=False, 

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

38 use_attribute_docstrings=True, 

39 model_title_generator=_node_title_generator, 

40): 

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

42 

43 @classmethod 

44 def model_validate( 

45 cls, 

46 obj: Union[Any, Dict[str, Any]], 

47 *, 

48 strict: Optional[bool] = None, 

49 from_attributes: Optional[bool] = None, 

50 context: Union[ValidationContext, Dict[str, Any], None] = None, 

51 ) -> Self: 

52 """Validate a pydantic model instance. 

53 

54 Args: 

55 obj: The object to validate. 

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

57 from_attributes: Whether to extract data from object attributes. 

58 context: Additional context to pass to the validator. 

59 

60 Raises: 

61 ValidationError: If the object failed validation. 

62 

63 Returns: 

64 The validated description instance. 

65 """ 

66 __tracebackhide__ = True 

67 

68 if context is None: 

69 context = validation_context_var.get() 

70 elif isinstance(context, dict): 

71 context = ValidationContext(**context) 

72 

73 assert not isinstance(obj, dict) or is_kwargs(obj), obj 

74 

75 with context: 

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

77 return super().model_validate( 

78 obj, strict=strict, from_attributes=from_attributes 

79 )