Coverage for src/bioimageio/spec/_internal/field_warning.py: 89%

66 statements  

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

1from __future__ import annotations 

2 

3import dataclasses 

4import inspect 

5from typing import TYPE_CHECKING, Any, Literal 

6 

7import pydantic.functional_validators 

8from annotated_types import BaseMetadata, GroupedMetadata 

9from loguru import logger 

10from pydantic import TypeAdapter 

11from pydantic_core import PydanticCustomError 

12from pydantic_core.core_schema import ( 

13 NoInfoValidatorFunction, 

14 ValidationInfo, 

15 WithInfoValidatorFunction, 

16) 

17from typing_extensions import LiteralString, TypeForm 

18 

19from .validation_context import get_validation_context 

20from .warning_levels import WARNING, WarningSeverity 

21 

22if TYPE_CHECKING: 

23 from pydantic.functional_validators import _V2Validator # type: ignore 

24 

25 

26ValidatorFunction = NoInfoValidatorFunction | WithInfoValidatorFunction 

27 

28AnnotationMetaData = BaseMetadata | GroupedMetadata 

29 

30 

31def warn( 

32 typ: TypeForm[Any], 

33 msg: LiteralString, # warning message, e.g. "'{value}' incompatible with {typ} 

34 severity: WarningSeverity = WARNING, 

35): 

36 """treat a type validation as a warning""" 

37 validator: TypeAdapter[Any] = TypeAdapter(typ) 

38 

39 return AfterWarner( 

40 validator.validate_python, severity=severity, msg=msg, context={"typ": typ} 

41 ) 

42 

43 

44def _call_validator_func( 

45 func: _V2Validator, 

46 mode: Literal["after", "before", "plain", "wrap"], 

47 value: Any, 

48 info: ValidationInfo, 

49) -> Any: 

50 # determine if validator needs info arg 

51 # logic adapted from pydantic._internal._decorators.py v2.11.10 

52 sig = inspect.signature(func) 

53 parameters = list(sig.parameters.values()) 

54 n_positional = sum( 

55 1 

56 for param in parameters 

57 if param.kind 

58 in (inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD) 

59 # First argument is the value being validated/serialized, and can have a default value 

60 # (e.g. `float`, which has signature `(x=0, /)`). We assume other parameters (the info arg 

61 # for instance) should be required, and thus without any default value. 

62 and (param.default is inspect.Parameter.empty or param is parameters[0]) 

63 ) 

64 needs_info = None 

65 if mode == "wrap": 

66 if n_positional == 3: 

67 needs_info = True 

68 elif n_positional == 2: 

69 needs_info = False 

70 else: 

71 assert mode in {"before", "after", "plain"}, ( 

72 f"invalid mode: {mode!r}, expected 'before', 'after' or 'plain" 

73 ) 

74 if n_positional == 2: 

75 needs_info = True 

76 elif n_positional == 1: 

77 needs_info = False 

78 

79 assert needs_info is not None, "could not determine if validator needs info arg" 

80 if needs_info: 

81 return func(value, info) # type: ignore 

82 else: 

83 return func(value) # type: ignore 

84 

85 

86def as_warning( 

87 func: _V2Validator, 

88 *, 

89 mode: Literal["after", "before", "plain", "wrap"] = "after", 

90 severity: WarningSeverity = WARNING, 

91 msg: LiteralString | None = None, 

92 msg_context: dict[str, Any] | None = None, 

93) -> ValidatorFunction: 

94 """turn validation function into a no-op, based on warning level""" 

95 

96 def wrapper(value: Any, info: ValidationInfo) -> Any: 

97 try: 

98 _call_validator_func(func, mode, value, info) 

99 except (AssertionError, ValueError) as e: 

100 issue_warning( 

101 msg or ",".join(e.args), 

102 field=info.field_name, 

103 log_depth=1, 

104 msg_context=msg_context, 

105 severity=severity, 

106 value=value, 

107 ) 

108 

109 return value 

110 

111 return wrapper 

112 

113 

114@dataclasses.dataclass(frozen=True, slots=True) 

115class AfterWarner(pydantic.functional_validators.AfterValidator): 

116 """Like AfterValidator, but wraps validation `func` `as_warning`""" 

117 

118 severity: WarningSeverity = WARNING 

119 msg: LiteralString | None = None 

120 context: dict[str, Any] | None = None 

121 

122 def __post_init__(self): 

123 object.__setattr__( 

124 self, 

125 "func", 

126 as_warning( 

127 self.func, 

128 mode="after", 

129 severity=self.severity, 

130 msg=self.msg, 

131 msg_context=self.context, 

132 ), 

133 ) 

134 

135 

136@dataclasses.dataclass(frozen=True, slots=True) 

137class BeforeWarner(pydantic.functional_validators.BeforeValidator): 

138 """Like BeforeValidator, but wraps validation `func` `as_warning`""" 

139 

140 severity: WarningSeverity = WARNING 

141 msg: LiteralString | None = None 

142 context: dict[str, Any] | None = None 

143 

144 def __post_init__(self): 

145 object.__setattr__( 

146 self, 

147 "func", 

148 as_warning( 

149 self.func, 

150 mode="before", 

151 severity=self.severity, 

152 msg=self.msg, 

153 msg_context=self.context, 

154 ), 

155 ) 

156 

157 

158# TODO: add `loc: Loc` to `issue_warning()` 

159# and use a loguru handler to format warnings accordingly 

160def issue_warning( 

161 msg: LiteralString, 

162 *, 

163 value: Any, 

164 severity: WarningSeverity = WARNING, 

165 msg_context: dict[str, Any] | None = None, 

166 field: str | None = None, 

167 log_depth: int = 1, 

168): 

169 msg_context = {"value": value, "severity": severity, **(msg_context or {})} 

170 

171 if severity >= (ctxt := get_validation_context()).warning_level: 

172 raise PydanticCustomError("warning", msg, msg_context) 

173 elif ctxt.log_warnings: 

174 log_msg = (field + ": " if field else "") + (msg.format(**msg_context)) 

175 logger.opt(depth=log_depth).log(severity, log_msg)