Coverage for src/bioimageio/spec/_internal/utils.py: 97%

91 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 re 

5from collections.abc import Callable, Iterable 

6from dataclasses import dataclass 

7from functools import cache as cache 

8from functools import wraps 

9from importlib.resources import files as files 

10from inspect import isfunction, signature 

11from typing import ( 

12 Any, 

13 TypeVar, 

14) 

15 

16import pydantic 

17from exceptiongroup import ExceptionGroup 

18from ruyaml import Optional 

19from typing_extensions import ParamSpec 

20 

21K = TypeVar("K") 

22V = TypeVar("V") 

23 

24 

25def get_format_version_tuple(format_version: Any) -> Optional[tuple[int, int, int]]: 

26 if ( 

27 not isinstance(format_version, str) 

28 or format_version.count(".") != 2 

29 or any(not v.isdigit() for v in format_version.split(".")) 

30 ): 

31 return None 

32 

33 parsed = tuple(map(int, format_version.split("."))) 

34 assert len(parsed) == 3 

35 return parsed 

36 

37 

38FirstK = TypeVar("FirstK") 

39 

40 

41def unindent(text: str, ignore_first_line: bool = False): 

42 """remove minimum count of spaces at beginning of each line. 

43 

44 Args: 

45 text: indented text 

46 ignore_first_line: allows to correctly unindent doc strings 

47 """ 

48 first = int(ignore_first_line) 

49 lines = text.split("\n") 

50 filled_lines = [line for line in lines[first:] if line] 

51 if len(filled_lines) < 2: 

52 return "\n".join(line.strip() for line in lines) 

53 

54 indent = min(len(line) - len(line.lstrip(" ")) for line in filled_lines) 

55 return "\n".join(lines[:first] + [line[indent:] for line in lines[first:]]) 

56 

57 

58T = TypeVar("T") 

59P = ParamSpec("P") 

60 

61 

62def assert_all_params_set_explicitly(fn: Callable[P, T]) -> Callable[P, T]: 

63 @wraps(fn) 

64 def wrapper(*args: P.args, **kwargs: P.kwargs): 

65 n_args = len(args) 

66 missing: set[str] = set() 

67 

68 for p in signature(fn).parameters.values(): 

69 if p.kind == p.POSITIONAL_ONLY: 

70 if n_args == 0: 

71 missing.add(p.name) 

72 else: 

73 n_args -= 1 # 'use' positional arg 

74 elif p.kind == p.POSITIONAL_OR_KEYWORD: 

75 if n_args == 0: 

76 if p.name not in kwargs: 

77 missing.add(p.name) 

78 else: 

79 n_args -= 1 # 'use' positional arg 

80 elif p.kind in (p.VAR_POSITIONAL, p.VAR_KEYWORD): 

81 pass 

82 elif p.kind == p.KEYWORD_ONLY and p.name not in kwargs: 

83 missing.add(p.name) 

84 

85 assert not missing, f"parameters {missing} of {fn} are not set explicitly" 

86 

87 return fn(*args, **kwargs) 

88 

89 return wrapper 

90 

91 

92def get_os_friendly_file_name(name: str) -> str: 

93 return re.sub(r"\W+|^(?=\d)", "_", name) 

94 

95 

96@dataclass 

97class _PrettyDataClassReprMixin: 

98 """A mixin that provides a pretty __repr__ for dataclasses 

99 

100 - leaving out fields that are None 

101 - leaving out memory locations of functions 

102 """ 

103 

104 def __repr__(self): 

105 field_values = { 

106 f.name: v 

107 for f in dataclasses.fields(self) 

108 if (v := getattr(self, f.name)) is not None 

109 } 

110 field_str = ", ".join( 

111 f"{k}=" + (f"<function {v.__name__}>" if isfunction(v) else repr(v)) 

112 for k, v in field_values.items() 

113 ) 

114 return f"{self.__class__.__name__}({field_str})" 

115 

116 

117class PrettyPlainSerializer(pydantic.PlainSerializer, _PrettyDataClassReprMixin): 

118 pass 

119 

120 

121class PrettyWrapSerializer(pydantic.WrapSerializer, _PrettyDataClassReprMixin): 

122 pass 

123 

124 

125def try_all( 

126 funcs: Iterable[Callable[P, T]], 

127 *args: P.args, 

128 **kwargs: P.kwargs, 

129) -> T: 

130 ret, errors = _try_all(funcs, False, *args, **kwargs) 

131 if errors: 

132 raise ExceptionGroup("All functions raised", errors) 

133 

134 assert not isinstance(ret, _AllFailedSentinel) 

135 return ret 

136 

137 

138def try_all_raise_last( 

139 funcs: Iterable[Callable[P, T]], 

140 *args: P.args, 

141 **kwargs: P.kwargs, 

142) -> T: 

143 ret, errors = _try_all(funcs, True, *args, **kwargs) 

144 if errors: 

145 raise errors[-1] 

146 

147 assert not isinstance(ret, _AllFailedSentinel) 

148 return ret 

149 

150 

151class _AllFailedSentinel: 

152 pass 

153 

154 

155def _try_all( 

156 funcs: Iterable[Callable[P, T]], 

157 raise_last_only: bool, 

158 *args: P.args, 

159 **kwargs: P.kwargs, 

160) -> tuple[_AllFailedSentinel | T, list[Exception]]: 

161 """Try to call each of the functions `funcs` with the given arguments. 

162 

163 If all raise, raise an exception group (or the last). 

164 

165 Returns: 

166 Result of the first successful call. 

167 """ 

168 errors: list[Exception] = [] 

169 for c in funcs: 

170 try: 

171 return c(*args, **kwargs), [] 

172 except Exception as e: 

173 errors.append(e) 

174 

175 if errors: 

176 errors.append(RuntimeError("No functions provided to try.")) 

177 

178 return _AllFailedSentinel(), errors