Coverage for src/chrisjen/utilities.py: 99%

145 statements  

« prev     ^ index     » next       coverage.py v7.17.0, created at 2026-11-14 09:29 +0000

1"""Shared tools. 

2 

3Contents: 

4 accepted_arguments: limits keyword arguments to those a function accepts. 

5 flatten_dict: returns the values of a nested `dict` in one level. 

6 import_object: imports an object from its import path. 

7 label_path: returns the label of a path: the names of its nodes. 

8 listify_names: returns a `list` of names from a setting. 

9 

10""" 

11 

12from __future__ import annotations 

13 

14import abc 

15import importlib 

16import inspect 

17import re 

18from collections.abc import MutableMapping 

19from typing import TYPE_CHECKING, Any 

20 

21if TYPE_CHECKING: 

22 from collections.abc import Callable, Hashable, Iterable, Mapping, Sequence 

23 

24 

25def accepted_arguments( 

26 function: Callable[..., Any], arguments: Mapping[str, Any] 

27) -> dict[str, Any]: 

28 """Returns the `arguments` that `function` can accept as keywords. 

29 

30 If `function` takes `**kwargs` (or its signature cannot be inspected), all 

31 of `arguments` are returned. 

32 

33 Args: 

34 function: callable to examine. 

35 arguments: keyword arguments to filter. 

36 

37 Returns: 

38 A `dict` of the `arguments` that `function` accepts. 

39 

40 """ 

41 try: 

42 parameters = inspect.signature(function).parameters 

43 except (TypeError, ValueError): 

44 return dict(arguments) 

45 if any( 

46 p.kind is inspect.Parameter.VAR_KEYWORD for p in parameters.values() 

47 ): 

48 return dict(arguments) 

49 return {k: v for k, v in arguments.items() if k in parameters} 

50 

51 

52def import_object(path: str) -> Any: 

53 """Imports an object (such as a function or class) from its import path. 

54 

55 The path can be dotted (`"statistics.fmean"` or 

56 `"sklearn.preprocessing.StandardScaler"`) or use a colon between the module 

57 and the attributes (`"package.module:Class.method"`). With a dotted path, 

58 the longest prefix that is a module is imported and the rest are attributes. 

59 

60 Args: 

61 path: import path of the object. 

62 

63 Raises: 

64 ImportError: if no module or attribute matches `path`. 

65 

66 Returns: 

67 The imported object. 

68 

69 """ 

70 if ':' in path: 

71 module_name, _, attribute_path = path.partition(':') 

72 candidates = [(module_name, attribute_path.split('.'))] 

73 else: 

74 parts = path.split('.') 

75 candidates = [ 

76 ('.'.join(parts[:cut]), parts[cut:]) 

77 for cut in range(len(parts), 0, -1) 

78 ] 

79 for module_name, attributes in candidates: 

80 try: 

81 item = importlib.import_module(module_name) 

82 except ModuleNotFoundError as error: 

83 # Only a missing candidate module means to try a shorter prefix. 

84 # A module that is found but is missing one of its own imports is 

85 # a real problem, so it is not hidden. 

86 missing = error.name or '' 

87 if module_name == missing or module_name.startswith(f'{missing}.'): 

88 continue 

89 raise 

90 try: 

91 for attribute in attributes: 

92 item = getattr(item, attribute) 

93 except AttributeError as error: 

94 message = f'cannot import {path!r}: {error}' 

95 raise ImportError(message) from error 

96 return item 

97 message = f'cannot import {path!r}: no module of that name was found' 

98 raise ImportError(message) 

99 

100 

101def flatten_dict(item: MutableMapping[str, Any]) -> dict[str, Any]: 

102 """Returns the values of a nested `dict` that are not `dict`s, in one level. 

103 

104 The keys of the nested `dict`s themselves are dropped. 

105 

106 Args: 

107 item: nested `dict` to flatten. 

108 

109 Returns: 

110 A flat `dict` of the keys and values at every level whose values are 

111 not nested `dict`s. If a key is at more than one level, the first 

112 one found is kept. 

113 

114 """ 

115 flat: dict[str, Any] = {} 

116 for key, value in item.items(): 

117 if isinstance(value, MutableMapping): 

118 for nested_key, nested_value in flatten_dict(value).items(): 

119 flat.setdefault(nested_key, nested_value) 

120 else: 

121 flat.setdefault(key, value) 

122 return flat 

123 

124 

125def label_path(path: Sequence[Hashable]) -> str: 

126 """Returns the label of `path`: the names of its nodes, joined by " > ". 

127 

128 Args: 

129 path: nodes in a path through a worker. 

130 

131 Returns: 

132 The label of `path`. A node without a `name` is labeled by its `str` 

133 form. 

134 

135 """ 

136 return ' > '.join(str(getattr(node, 'name', node)) for node in path) 

137 

138 

139def listify_names(item: Any) -> list[str]: 

140 """Returns a `list` of names from a setting. 

141 

142 Args: 

143 item: a `str` of names separated by commas, a sequence of names (each 

144 of which may also have commas), or `None`. 

145 

146 Returns: 

147 The names, with whitespace removed and empty names dropped. 

148 

149 """ 

150 return [ 

151 part.strip() 

152 for value in _iterify(item) 

153 for part in str(value).split(',') 

154 if part.strip()] 

155 

156 

157# The private names of `flatten_dict`, `label_path`, and `listify_names`, 

158# which packages built on `chrisjen` used before they were public. 

159_flatten_dict = flatten_dict 

160_label_path = label_path 

161_listify_names = listify_names 

162 

163 

164""" Private Functions """ 

165 

166# Marks a name that was not found (`None` could be a stored value). 

167_MISSING = object() 

168 

169 

170def _all_classes(layer: MutableMapping[str, Any]) -> dict[str, type]: 

171 """Returns the stored classes in a nested `dict`, at every level. 

172 

173 Args: 

174 layer: nested `dict` of names that map to classes or nested `dict`s. 

175 

176 Returns: 

177 A flat `dict` of the names and classes. If a name is in more than one 

178 place, the first one found is kept. 

179 

180 """ 

181 classes: dict[str, type] = {} 

182 for name, value in layer.items(): 

183 if isinstance(value, dict): 

184 classes.update(_all_classes(value)) 

185 else: 

186 classes.setdefault(name, value) 

187 return classes 

188 

189 

190def _all_genres(layer: MutableMapping[str, Any]) -> list[str]: 

191 """Returns the names of the nested `dict`s (genres), at every level. 

192 

193 Args: 

194 layer: nested `dict` of names that map to classes or nested `dict`s. 

195 

196 Returns: 

197 The names that map to nested `dict`s, depth first. 

198 

199 """ 

200 genres: list[str] = [] 

201 for name, value in layer.items(): 

202 if isinstance(value, dict): 

203 genres.append(name) 

204 genres.extend(_all_genres(value)) 

205 return genres 

206 

207 

208def _apply_path(path: Sequence[Any], item: Any, **kwargs: Any) -> Any: 

209 """Applies each node in `path`, in order, to `item`. 

210 

211 Args: 

212 path: nodes with an `apply` method. 

213 item: data or object to change. 

214 **kwargs: keyword arguments passed to each node. 

215 

216 Returns: 

217 The result of the last node. 

218 

219 """ 

220 for node in path: 

221 item = node.apply(item, **kwargs) 

222 return item 

223 

224 

225def _average(items: Iterable[Any]) -> Any: 

226 """Returns the mean of `items`. 

227 

228 This works for numbers and for any objects that support addition and 

229 division by an `int` (e.g., `numpy` arrays or `pandas` objects). The items 

230 are added up one at a time, so `items` can be a generator whose items are 

231 made only as they are needed. 

232 

233 Args: 

234 items: results to average. 

235 

236 Raises: 

237 ValueError: if `items` is empty. 

238 TypeError: if `items` cannot be added together and divided by an 

239 `int`. 

240 

241 Returns: 

242 The mean of `items`. 

243 

244 """ 

245 total: Any = None 

246 count = 0 

247 try: 

248 for item in items: 

249 total = item if count == 0 else total + item 

250 count += 1 

251 if count == 0: 

252 message = 'cannot average an empty sequence' 

253 raise ValueError(message) 

254 return total / count 

255 except TypeError as error: 

256 message = ( 

257 f'cannot average results of type {type(total).__name__}: they ' 

258 f'must support addition and division by an int' 

259 ) 

260 raise TypeError(message) from error 

261 

262 

263def _find(layer: MutableMapping[str, Any], name: str) -> Any: 

264 """Returns the first value named `name` in a nested `dict`, at any level. 

265 

266 Args: 

267 layer: nested `dict` to search. 

268 name: key to find. 

269 

270 Returns: 

271 The value of `name`, or `_MISSING` if `name` is not in `layer`. 

272 

273 """ 

274 if name in layer: 

275 return layer[name] 

276 for value in layer.values(): 

277 if isinstance(value, dict): 

278 found = _find(value, name) 

279 if found is not _MISSING: 

280 return found 

281 return _MISSING 

282 

283 

284def _find_genre( 

285 layer: MutableMapping[str, Any], 

286 name: str, 

287 genre: str | None = None) -> str | object | None: 

288 """Returns the name of the nested `dict` (genre) that `name` is in. 

289 

290 Args: 

291 layer: nested `dict` to search. 

292 name: key to find. 

293 genre: name of `layer` itself. Defaults to `None`, which is the top 

294 level. 

295 

296 Returns: 

297 The name of the innermost `dict` that holds `name`, `None` if it is at 

298 the top level, or `_MISSING` if `name` is not in `layer`. 

299 

300 """ 

301 if name in layer: 

302 return genre 

303 for key, value in layer.items(): 

304 if isinstance(value, dict): 

305 found = _find_genre(value, name, key) 

306 if found is not _MISSING: 

307 return found 

308 return _MISSING 

309 

310 

311def _get_path( 

312 item: type, 

313 root: type, 

314 namer: Callable[[type], str]) -> list[str]: 

315 """Returns the names of the abstract ancestors of `item` below `root`. 

316 

317 It follows the first base of each class that is a subclass of `root`. 

318 

319 Args: 

320 item: subclass of `root`. 

321 root: class at which to stop. 

322 namer: function that returns the name of a class. 

323 

324 Returns: 

325 The names of the abstract ancestors of `item`, from just below `root` 

326 down. A direct subclass of `root` has an empty path. 

327 

328 """ 

329 path: list[str] = [] 

330 parent = next(base for base in item.__bases__ if issubclass(base, root)) 

331 while parent is not root: 

332 if _is_abstract(parent): 

333 path.insert(0, namer(parent)) 

334 parent = next( 

335 base for base in parent.__bases__ if issubclass(base, root)) 

336 return path 

337 

338 

339def _get_all_keys(item: MutableMapping[str, Any]) -> list[str]: 

340 """Returns `list` of all keys in a nested `dict`. 

341 

342 Args: 

343 item: mapping to find keys from. 

344 

345 Returns: 

346 All keys in the nested dictionary, at every level. 

347 

348 """ 

349 keys = [] 

350 for key, value in item.items(): 

351 keys.append(key) 

352 if isinstance(value, MutableMapping): 

353 keys.extend(_get_all_keys(value)) 

354 return keys 

355 

356 

357def _is_abstract(item: type) -> bool: 

358 """Returns whether `abc.ABC` is one of the bases of `item`. 

359 

360 Args: 

361 item: class to check. 

362 

363 Returns: 

364 Whether `item` lists `abc.ABC` among its bases. 

365 

366 """ 

367 return abc.ABC in item.__bases__ 

368 

369 

370def _iterify(item: Any) -> list[Any]: 

371 """Returns `item` as a `list`, but does not iterate `str` types. 

372 

373 Args: 

374 item: item to turn into a `list`. 

375 

376 Returns: 

377 A `list` of `item`. A `str` is stored as a single item, `None` becomes 

378 an empty `list`, and any other non-iterable is wrapped in a `list`. 

379 

380 """ 

381 if item is None: 

382 return [] 

383 if isinstance(item, str | bytes): 

384 return [item] 

385 try: 

386 return list(item) 

387 except TypeError: 

388 return [item] 

389 

390 

391def _namify(item: Any, default: str | None = None) -> str | None: 

392 """Returns `str` name representation of `item`. 

393 

394 Args: 

395 item: item to determine a `str` name for. 

396 default: default name to return if a name cannot be created. 

397 

398 Returns: 

399 A name for `item`: `item` itself if it is a `str`, the `name` of an 

400 instance that has a `str` name, or the snake case name of its 

401 class. 

402 

403 """ 

404 if isinstance(item, str): 

405 return item 

406 elif ( 

407 hasattr(item, 'name') 

408 and not inspect.isclass(item) 

409 and isinstance(item.name, str) 

410 ): 

411 return item.name 

412 else: 

413 try: 

414 return _snakify(item.__name__) 

415 except AttributeError: 

416 if item.__class__.__name__ is not None: 416 ↛ 419line 416 didn't jump to line 419 because the condition on line 416 was always true

417 return _snakify(item.__class__.__name__) 

418 else: 

419 return default 

420 

421 

422def _snakify(item: str) -> str: 

423 """Converts a capitalized `str` to snake case. 

424 

425 Args: 

426 item: `str` to convert. 

427 

428 Returns: 

429 `item` converted to snake case. 

430 

431 """ 

432 item = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', item) 

433 return re.sub('([a-z0-9])([A-Z])', r'\1_\2', item).lower()