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

258 statements  

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

1"""Base classes for a project. 

2 

3Contents: 

4 Library: stores `Genre` classes in the hierarchy of their subclasses. 

5 library: the `Library` that `Genre` subclasses are added to. 

6 Genre: base class for every class that is stored in the `library`. 

7 Idea: settings of a project, with properties for building its workflow. 

8 Vertex: base class for nodes in a project workflow. 

9 Criteria: scores the results of a workflow. 

10 Report: base class for reports that describe a project. 

11 

12""" 

13 

14from __future__ import annotations 

15 

16import abc 

17import dataclasses 

18import functools 

19import inspect 

20from collections.abc import Callable, Iterator, MutableMapping, Sequence 

21from typing import TYPE_CHECKING, Any, Self, TypeAlias 

22 

23import bobbie 

24import camina 

25import holden 

26 

27from . import options, utilities 

28 

29if TYPE_CHECKING: 

30 from . import interface 

31 

32 

33# Keyword arguments, such as the `parameters` of a node. 

34GenericDict: TypeAlias = MutableMapping[str, Any] 

35# A layer of `Library.contents`: names of genres (abstract classes) map to 

36# nested layers and names of other classes map to the classes. 

37Layer: TypeAlias = MutableMapping[str, Any] 

38# Fields of a `Vertex` that are not filled from settings by `Vertex.build`. 

39# Criteria are named by the "criterion" setting and built separately. 

40_NOT_SETTINGS: tuple[str, ...] = ( 

41 'name', 'contents', 'parameters', 'criteria', 'default_factory') 

42# Attribute that marks an `apply` method that `_wrap_apply` has wrapped. 

43_WRAPPED: str = '_chrisjen_wrapped' 

44 

45 

46@dataclasses.dataclass 

47class Library(MutableMapping[str, Any]): 

48 """Stores `Genre` classes in the hierarchy of their subclasses. 

49 

50 `contents` is a nested `dict` that follows the subclasses of `Genre`. An 

51 abstract class (one that lists `abc.ABC` among its bases) is only a key: its 

52 value is a new layer for its subclasses, and the class itself is not 

53 stored. Any other class is stored, under its name, in the layer of its 

54 nearest abstract ancestor (or at the top level, if it has none). For 

55 example, `Vertex`, `Step`, and `Worker` are abstract, so if `Scaler` is a 

56 subclass of `Technique` and `Scale` is a subclass of `Step`: 

57 

58 ```py 

59 { 

60 'vertex': { 

61 'technique': Technique, 

62 'scaler': Scaler, 

63 'step': {'scale': Scale}, 

64 'worker': {'flow': Flow, 'contest': Contest}, 

65 } 

66 } 

67 ``` 

68 

69 A class can also be added under another name (`NullVertex` is also stored 

70 as "none"). `all` is a flat `dict` of every stored class, and `borrow` 

71 finds classes by name. 

72 

73 Attributes: 

74 contents: nested dictionary of `Genre` subclasses. Keys are the names of 

75 the subclasses (by default, snake case versions of their class 

76 names). Values are either subclasses or nested dictionaries 

77 containing subclasses. 

78 

79 """ 

80 

81 contents: Layer = dataclasses.field(default_factory = dict) 

82 

83 """ Properties """ 

84 

85 @property 

86 def genres(self) -> list[str]: 

87 """Returns names of the genres (abstract classes) at every level.""" 

88 return utilities._all_genres(self.contents) 

89 

90 @property 

91 def plurals(self) -> list[str]: 

92 """Returns a list of pluralized names of genres.""" 

93 return list(camina.add_suffix_to_list(self.genres, 's')) 

94 

95 @property 

96 def all(self) -> dict[str, type]: 

97 """Returns a flattened dictionary of all classes in the library.""" 

98 return utilities.flatten_dict(self.contents) 

99 

100 """ Public Methods """ 

101 

102 def add(self, item: type, name: str | None = None) -> None: 

103 """Adds `item` to its place in `contents`. 

104 

105 An abstract class (one that lists `abc.ABC` among its bases) adds a 

106 new, empty layer named for it, unless that layer already exists. Any 

107 other class is stored under its name in the layer of its nearest 

108 abstract ancestor. A direct subclass of `Genre` is at the top level. 

109 

110 Args: 

111 item: `Genre` subclass to add. 

112 name: name to store `item` under. Defaults to `None`, which uses 

113 the snake case name of the class. 

114 

115 Raises: 

116 TypeError: if `item` is not a subclass of `Genre`. 

117 ValueError: if `item` is `Genre` itself, or if its name is already 

118 used in the same layer for a different kind of entry (a class 

119 where a layer is, or a layer where a class is). 

120 

121 """ 

122 if not (inspect.isclass(item) and issubclass(item, Genre)): 

123 message = f'item must be a subclass of Genre, not {item!r}' 

124 raise TypeError(message) 

125 if item is Genre: 

126 message = 'Genre itself cannot be added: add its subclasses' 

127 raise ValueError(message) 

128 name = self._get_name(item, name) 

129 layer = self._get_layer( 

130 utilities._get_path(item, Genre, self._get_name)) 

131 existing = layer.get(name) 

132 if utilities._is_abstract(item): 

133 if existing is not None and not isinstance(existing, dict): 

134 message = ( 

135 f'{name!r} is already a stored class, so the abstract ' 

136 f'class {item.__name__} cannot form a genre with it' 

137 ) 

138 raise ValueError(message) 

139 # Keeps the layer (and what is in it) if it already exists. 

140 layer.setdefault(name, {}) 

141 else: 

142 if isinstance(existing, dict): 

143 message = ( 

144 f'{name!r} is already a genre, so the class ' 

145 f'{item.__name__} cannot be stored with that name' 

146 ) 

147 raise ValueError(message) 

148 layer[name] = item 

149 

150 def borrow( 

151 self, 

152 names: str | Sequence[str], 

153 genre: str | type[Genre] | None = None) -> type[Genre]: 

154 """Returns the first class found that is named in `names`. 

155 

156 Listing more than one name allows a specific class to be used if it 

157 exists, with a general one as a fallback. For example, a worker named 

158 "analyst" can use an `Analyst` class, if there is one, and otherwise 

159 the class of its design. 

160 

161 Args: 

162 names: name or names of classes, in the order to look for them. 

163 genre: name of the genre (or the abstract class) to look in. 

164 Defaults to `None`, which looks in the whole library. 

165 

166 Raises: 

167 KeyError: if none of `names` are in the library (or `genre`), or 

168 if `genre` is not a genre in the library. 

169 

170 Returns: 

171 The first class found. 

172 

173 """ 

174 if genre is None: 

175 classes = self.all 

176 else: 

177 classes = utilities.flatten_dict(self.get_genre(genre)) 

178 for name in utilities._iterify(names): 

179 if name in classes: 

180 return classes[name] 

181 message = f'no class named {names!r} is in the library' 

182 raise KeyError(message) 

183 

184 def classify(self, item: str | type[Genre] | Genre) -> str: 

185 """Returns the genre (abstract base class) that `item` is in. 

186 

187 Args: 

188 item: `Genre` subclass, subclass instance, or its name. 

189 

190 Raises: 

191 ValueError: if `item` is not in the library, or if it is at the 

192 top level of the library (and so is not in a genre). 

193 

194 Returns: 

195 The name of the genre to which `item` belongs: the innermost layer 

196 that it is in. 

197 

198 """ 

199 genre: str | None 

200 if isinstance(item, str): 

201 found = utilities._find_genre(self.contents, item) 

202 if found is utilities._MISSING: 

203 message = f'{item!r} is not in the library' 

204 raise ValueError(message) 

205 genre = found if isinstance(found, str) else None 

206 else: 

207 if not inspect.isclass(item): 

208 item = item.__class__ 

209 if not issubclass(item, Genre) or item is Genre: 

210 message = f'{item!r} is not in the library' 

211 raise ValueError(message) 

212 path = utilities._get_path(item, Genre, self._get_name) 

213 genre = path[-1] if path else None 

214 if genre is None: 

215 message = f'{item!r} is at the top level, so it is not in a genre' 

216 raise ValueError(message) 

217 return genre 

218 

219 def delete(self, item: str) -> None: 

220 """Deletes the class or layer named `item`, wherever it is. 

221 

222 Deleting a layer deletes everything in it. 

223 

224 Args: 

225 item: name of a class or a layer. 

226 

227 Raises: 

228 KeyError: if `item` is not in `contents`. 

229 

230 """ 

231 removed: set[str] = set() 

232 def remove(layer: Layer) -> None: 

233 for key in list(layer): 

234 value = layer[key] 

235 if key == item: 

236 removed.add(key) 

237 if isinstance(value, dict): 

238 removed.update(utilities._get_all_keys(value)) 

239 del layer[key] 

240 elif isinstance(value, dict): 

241 remove(value) 

242 remove(self.contents) 

243 if not removed: 

244 message = f'{item!r} is not in the library' 

245 raise KeyError(message) 

246 

247 def get_genre( 

248 self, 

249 item: str | type[Genre]) -> Layer: 

250 """Returns the layer of `contents` formed by a genre abstract class. 

251 

252 Args: 

253 item: abstract `Genre` subclass or its name. 

254 

255 Raises: 

256 KeyError: if there is no layer for `item`. 

257 

258 Returns: 

259 The nested `dict` of the subclasses of `item`. 

260 

261 """ 

262 name = item if isinstance(item, str) else self._get_name(item) 

263 found = utilities._find(self.contents, name) 

264 if not isinstance(found, dict): 

265 message = f'{name!r} is not a layer of the library' 

266 raise KeyError(message) 

267 return found 

268 

269 """ Private Methods """ 

270 

271 def _get_layer(self, path: list[str]) -> Layer: 

272 """Returns the layer at `path`, creating any layers that are missing. 

273 

274 Args: 

275 path: names of the genres that lead to the layer, from the top 

276 level of `contents` down. 

277 

278 Returns: 

279 The nested `dict` at `path`. 

280 

281 """ 

282 layer = self.contents 

283 for key in path: 

284 layer = layer.setdefault(key, {}) 

285 return layer 

286 

287 @staticmethod 

288 def _get_name(item: type[Genre], name: str | None = None) -> str: 

289 """Returns `name` or the name to store `item` under. 

290 

291 Args: 

292 item: `Genre` subclass to name. 

293 name: name to use. Defaults to `None`, which uses the snake case 

294 name of `item`. 

295 

296 Returns: 

297 The name for `item`. 

298 

299 """ 

300 return ( 

301 name 

302 or options._KEY_NAMER(item) 

303 or utilities._snakify(item.__name__)) 

304 

305 """ Dunder Methods """ 

306 

307 def __getitem__(self, key: str) -> Any: 

308 """Returns value for `key` at the top level of `contents`. 

309 

310 Args: 

311 key: key in `contents` for which a value is sought. 

312 

313 Returns: 

314 Value stored in `contents`: a layer or a class. 

315 

316 """ 

317 return self.contents[key] 

318 

319 def __setitem__( 

320 self, key: str, 

321 value: type[Genre] | dict[str, type[Genre]]) -> None: 

322 """Adds `value` to the library under the name `key`. 

323 

324 A `Genre` subclass is added to its place in `contents` (see `add`). A 

325 dictionary of subclasses is stored as is, as a genre at the top level. 

326 

327 Args: 

328 key: name to store `value` under. 

329 value: `Genre` subclass or dictionary of subclasses. 

330 

331 """ 

332 if isinstance(value, dict): 

333 self.contents[key] = value 

334 else: 

335 self.add(value, name = key) 

336 

337 def __delitem__(self, item: str) -> None: 

338 """Deletes the class or layer named `item`. 

339 

340 Args: 

341 item: name of a class or layer, at any level. 

342 

343 Raises: 

344 KeyError: if `item` is not in `contents`. 

345 

346 """ 

347 self.delete(item) 

348 

349 def __add__(self, other: type[Genre]) -> Library: 

350 """Adds `other` to the library using the `add` method. 

351 

352 Args: 

353 other: `Genre` subclass to add. 

354 

355 Returns: 

356 This library. 

357 

358 """ 

359 self.add(other) 

360 return self 

361 

362 def __iter__(self) -> Iterator[str]: 

363 """Returns iterator of the top level of `contents`. 

364 

365 Returns: 

366 Iterator of `contents`. 

367 

368 """ 

369 return iter(self.contents) 

370 

371 def __len__(self) -> int: 

372 """Returns length of the top level of `contents`. 

373 

374 Returns: 

375 Length of `contents`. 

376 

377 """ 

378 return len(self.contents) 

379 

380 

381library: Library = Library() 

382 

383 

384@dataclasses.dataclass 

385class Genre(abc.ABC): # noqa: B024 

386 """Stores itself in the project library. 

387 

388 Every subclass of `Genre` is added to `library` when it is defined. A 

389 subclass that lists `abc.ABC` among its bases is abstract: it forms a new 

390 layer of `Library.contents`. Any other subclass is stored in the layer of 

391 its nearest abstract ancestor. 

392 

393 """ 

394 

395 """ Initialization Methods """ 

396 

397 @classmethod 

398 def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: 

399 """Automatically adds subclasses to the library.""" 

400 super().__init_subclass__(*args, **kwargs) 

401 library.add(cls) 

402 

403 

404@dataclasses.dataclass 

405class Idea(bobbie.Settings, Genre): 

406 """Loads and stores configuration settings. 

407 

408 Idea is a subclass of the Settings class in the bobbie repo. See its 

409 documentation for information about its functionality. 

410 https://withprecedent.github.io/bobbie/ 

411 

412 Idea adds properties (`workers`, `steps`, `techniques`, `designs`, 

413 `criteria`, and `parameters`) and a `get_settings` method that read the 

414 parts of a `chrisjen` workflow from the settings. Its fields (`contents`, 

415 `default_factory`, and `name`) are those of `bobbie.Settings`. 

416 

417 """ 

418 

419 """ Properties """ 

420 

421 @property 

422 def criteria(self) -> dict[str, str]: 

423 """Returns the criteria of the workers and steps in the settings. 

424 

425 In each worker section, a "criterion" setting is the criterion of the 

426 worker and a "{name}_criterion" setting is the criterion of `name`. 

427 

428 Returns: 

429 A `dict` mapping names (the prefix of the setting, or the worker 

430 name for "criterion") to criteria. 

431 

432 """ 

433 return self._find_settings('criterion') 

434 

435 @property 

436 def designs(self) -> dict[str, str]: 

437 """Returns the designs of the workers in the settings. 

438 

439 In each worker section, a "design" setting is the design of the worker 

440 and a "{name}_design" setting is the design of `name`. A worker without 

441 a design uses `options._DEFAULT_DESIGN`. 

442 

443 Returns: 

444 A `dict` mapping names (the prefix of the setting, or the worker 

445 name for "design") to designs. 

446 

447 """ 

448 designs = self._find_settings('design') 

449 for worker in self.workers: 

450 # Uses the default design for a worker that does not name one. 

451 if worker not in designs: 

452 designs[worker] = options._DEFAULT_DESIGN 

453 return designs 

454 

455 @property 

456 def parameters(self) -> dict[str, dict[str, Any]]: 

457 """Returns the parameters sections of the settings. 

458 

459 Returns: 

460 A `dict` mapping the prefix of each section that ends in 

461 "_parameters" to that section. 

462 

463 """ 

464 parameters = {} 

465 for key, section in self.contents.items(): 

466 # Skips settings that are not sections or not named by a `str`. 

467 if not isinstance(key, str) or not isinstance( 

468 section, MutableMapping): 

469 continue 

470 # Stores each parameters section under the name before 

471 # "_parameters". 

472 if key.endswith('_parameters'): 

473 name = key.removesuffix('_parameters') 

474 parameters[name] = dict(section) 

475 return parameters 

476 

477 @property 

478 def steps(self) -> dict[str, list[str]]: 

479 """Returns the steps of the workers in the settings. 

480 

481 In each worker section, a "steps" setting lists the steps of the worker 

482 and a "{name}_steps" setting lists the steps of `name`. A "workers" or 

483 "{name}_workers" setting (as in the project section) lists steps the 

484 same way. 

485 

486 Returns: 

487 A `dict` mapping names (the prefix of the setting, or the worker 

488 name for "steps") to `list`s of step names. 

489 

490 """ 

491 found = self._find_settings('workers') 

492 found.update(self._find_settings('steps')) 

493 steps = {} 

494 for name, value in found.items(): 

495 # Converts a setting such as "clean, scale" to a list of names. 

496 steps[name] = utilities.listify_names(value) 

497 return steps 

498 

499 @property 

500 def techniques(self) -> dict[str, list[str]]: 

501 """Returns the techniques of the workers and steps in the settings. 

502 

503 In each worker section, a "techniques" setting lists the techniques of 

504 the worker and a "{name}_techniques" setting lists the techniques of 

505 `name` (usually a step). 

506 

507 Returns: 

508 A `dict` mapping names (the prefix of the setting, or the worker 

509 name for "techniques") to `list`s of technique names. 

510 

511 """ 

512 techniques = {} 

513 for name, value in self._find_settings('techniques').items(): 

514 # Converts a setting such as "min_max, standard" to a list of 

515 # names. 

516 techniques[name] = utilities.listify_names(value) 

517 return techniques 

518 

519 @property 

520 def workers(self) -> dict[str, MutableMapping[str, Any]]: 

521 """Returns the worker sections of the settings. 

522 

523 The project section (whose name ends in "_project") is included under 

524 the name of the project, the part before "_project", so its settings 

525 are found by the other properties as well. 

526 

527 Returns: 

528 A `dict` mapping the name of each section of `contents` that does 

529 not end in "parameters" and is not special (see 

530 `options.is_special_setting`) to that section. 

531 

532 """ 

533 workers = {} 

534 for key, section in self.contents.items(): 

535 # Skips settings that are not sections or not named by a `str`. 

536 if not isinstance(key, str) or not isinstance( 

537 section, MutableMapping): 

538 continue 

539 # Skips parameters sections and special sections (such as "files"). 

540 if key.endswith('parameters') or options.is_special_setting(key): 

541 continue 

542 # Stores the project section under the name of the project. 

543 name = key.removesuffix('_project') 

544 workers[name] = section 

545 return workers 

546 

547 """ Public Methods """ 

548 

549 def get_settings(self, name: str, keys: Sequence[str]) -> dict[str, Any]: 

550 """Returns the settings in `keys` that belong to `name`. 

551 

552 A setting belongs to `name` if it is in the section for `name` or if 

553 it is named "{name}_{key}" in any worker section. This is how settings 

554 such as "max_iterations" reach the class that `name` is built from. A 

555 key in `options._GENERAL_SETTINGS` (such as "conserve_memory") that 

556 does not belong to `name` is taken from the "general" section, if it 

557 is there. 

558 

559 Args: 

560 name: name of a worker, step, or technique. 

561 keys: names of the settings to look for. 

562 

563 Returns: 

564 A `dict` mapping each key in `keys` that is found to its value. 

565 

566 """ 

567 general = self.contents.get('general', {}) 

568 found = {} 

569 for key in keys: 

570 settings = self._find_settings(key) 

571 if name in settings: 

572 found[key] = settings[name] 

573 elif key in options._GENERAL_SETTINGS and key in general: 

574 found[key] = general[key] 

575 return found 

576 

577 """ Private Methods """ 

578 

579 def _find_settings(self, suffix: str) -> dict[str, Any]: 

580 """Returns the settings named `suffix` or ending in `_{suffix}`. 

581 

582 Args: 

583 suffix: name of the setting to find in each worker section. 

584 

585 Returns: 

586 A `dict` mapping names to the values of the settings. A setting 

587 named `suffix` is stored under the name of its worker section, 

588 and a setting named "{name}_{suffix}" under `name`. 

589 

590 """ 

591 found = {} 

592 for worker, section in self.workers.items(): 

593 for key, value in section.items(): 

594 # A setting such as "design" belongs to the worker itself. 

595 if key == suffix: 

596 found[worker] = value 

597 # A setting such as "clean_design" belongs to "clean". 

598 elif key.endswith(f'_{suffix}'): 

599 name = key.removesuffix(f'_{suffix}') 

600 found[name] = value 

601 return found 

602 

603 

604@dataclasses.dataclass 

605class Vertex(holden.Labeled, holden.Node, Genre, abc.ABC): 

606 """Base class for nodes in a `chrisjen` workflow. 

607 

608 Vertexes are hashed and compared by `name`, so a `str` equal to the name of 

609 a node can be used in its place. Each vertex is applied to an item with 

610 `apply` and can be built from a project's settings with `build`. The 

611 subclasses are in the `nodes` and `workers` modules. 

612 

613 A subclass writes `apply`. When the subclass is defined, its `apply` is 

614 wrapped so that each call to it goes through `_call_apply`, which adds 

615 `parameters` to the keyword arguments. A call to the `apply` of a parent 

616 class (through `super()`) is not wrapped again: it gets the keyword 

617 arguments exactly as they are passed. 

618 

619 Args: 

620 contents: item(s) to be applied to the `item` passed to `apply`. 

621 Defaults to `None`. 

622 name: name used to refer to the node in a workflow. Defaults to `None`, 

623 in which case the name is inferred from the class or `contents`. 

624 parameters: keyword arguments passed to `apply`. Defaults to an empty 

625 `dict`. 

626 

627 """ 

628 

629 contents: Any | None = None 

630 name: str | None = None 

631 parameters: GenericDict = dataclasses.field(default_factory = dict) 

632 

633 """ Initialization Methods """ 

634 

635 @classmethod 

636 def __init_subclass__(cls, *args: Any, **kwargs: Any) -> None: 

637 """Wraps the `apply` method of each subclass (see `_call_apply`).""" 

638 super().__init_subclass__(*args, **kwargs) 

639 # The method is found on the class, rather than in its own namespace, 

640 # so that an `apply` from a mixin that is not a vertex is wrapped too. 

641 method = cls.apply 

642 if not getattr(method, _WRAPPED, False): 

643 setattr(cls, 'apply', _wrap_apply(method)) # noqa: B010 

644 

645 """ Class Methods """ 

646 

647 @classmethod 

648 def build( 

649 cls, 

650 name: str, 

651 project: interface.Project, 

652 parameters: GenericDict | None = None, 

653 **kwargs: Any) -> Self: 

654 """Builds an instance named `name` from the settings of `project`. 

655 

656 Settings that belong to `name` (see `Idea.get_settings`) and match a 

657 field of the class are passed to the constructor, so a setting such as 

658 "max_iterations" reaches the class that uses it. The "{name}_parameters" 

659 section of the settings is added to the default parameters of the 

660 class. Subclasses can override this method to build themselves 

661 differently. 

662 

663 Args: 

664 name: name of the node. 

665 project: the project the node belongs to. 

666 parameters: more parameters, which take precedence over those in 

667 the settings. Defaults to `None`. 

668 **kwargs: other arguments for the constructor, which take 

669 precedence over the settings. 

670 

671 Returns: 

672 The built instance. 

673 

674 """ 

675 fields = [ 

676 field.name for field in dataclasses.fields(cls) 

677 if field.name not in _NOT_SETTINGS] 

678 settings = project.idea.get_settings(name, fields) 

679 vertex = cls(name = name, **{**settings, **kwargs}) 

680 vertex.parameters.update(project.idea.parameters.get(name, {})) 

681 vertex.parameters.update(parameters or {}) 

682 return vertex 

683 

684 """ Required Methods """ 

685 

686 @abc.abstractmethod 

687 def apply(self, item: Any, **kwargs: Any) -> Any: 

688 """Applies this node to `item`. 

689 

690 Args: 

691 item: data or object (often the result of the previous node) to 

692 which this node should be applied. 

693 **kwargs: keyword arguments, which take precedence over 

694 `parameters`. 

695 

696 Returns: 

697 The result of applying this node to `item`. 

698 

699 """ 

700 

701 """ Private Methods """ 

702 

703 def _call_apply( 

704 self, 

705 method: Callable[..., Any], 

706 item: Any, 

707 /, 

708 **kwargs: Any) -> Any: 

709 """Calls `method`, the `apply` of this node's class, with `parameters`. 

710 

711 Every call to `apply` goes through this method, except one made from a 

712 subclass through `super()`. Subclasses can override it to prepare the 

713 item or the result in the same way for every `apply`. 

714 

715 Args: 

716 method: the `apply` method, before it was wrapped. 

717 item: data or object to which this node should be applied. 

718 **kwargs: keyword arguments, which take precedence over 

719 `parameters`. 

720 

721 Returns: 

722 The result of `method`. 

723 

724 """ 

725 return method(self, item, **{**self.parameters, **kwargs}) 

726 

727 

728@dataclasses.dataclass 

729class Criteria(Genre, abc.ABC): 

730 """Scores the results of a workflow. 

731 

732 `Criteria` can be used directly, by wrapping a tool, or subclassed to 

733 override `score`. A `Contest` keeps the result with the highest score, and 

734 a `Benchmark` stops when `test` passes. 

735 

736 Args: 

737 contents: tool that scores a result: a callable or the import path of 

738 one. Defaults to `None`. 

739 parameters: keyword arguments passed to the tool. Defaults to an empty 

740 `dict`. 

741 

742 """ 

743 

744 contents: str | Callable[..., Any] | None = None 

745 parameters: GenericDict = dataclasses.field(default_factory = dict) 

746 

747 """ Public Methods """ 

748 

749 def score(self, item: Any) -> Any: 

750 """Returns the score of `item`. Higher scores are better. 

751 

752 Args: 

753 item: data or object to score. 

754 

755 Raises: 

756 NotImplementedError: if there is no tool in `contents` and a 

757 subclass does not override this method. 

758 

759 Returns: 

760 The result of calling the tool with `item` and `parameters`. 

761 

762 """ 

763 tool = self.contents 

764 if isinstance(tool, str): 

765 tool = utilities.import_object(tool) 

766 if tool is None: 

767 message = 'criteria has no tool: pass one as contents' 

768 raise NotImplementedError(message) 

769 return tool(item, **self.parameters) 

770 

771 def test(self, item: Any) -> bool: 

772 """Returns whether `item` meets the criteria (has a true score). 

773 

774 Args: 

775 item: data or object to test. 

776 

777 Returns: 

778 Whether the score of `item` is true. 

779 

780 """ 

781 return bool(self.score(item)) 

782 

783 

784@dataclasses.dataclass 

785class Report(Genre, abc.ABC): 

786 """Describes a project after it is applied. 

787 

788 `Project.apply` calls `generate` after each run of the workflow. 

789 

790 Args: 

791 contents: data for the report. Defaults to `None`. 

792 

793 """ 

794 

795 contents: Any = dataclasses.field(default = None) 

796 

797 """ Required Methods """ 

798 

799 @abc.abstractmethod 

800 def generate(self, project: interface.Project) -> Any: 

801 """Generates the report for `project`. 

802 

803 Args: 

804 project: the project to report on, after it has been applied. 

805 

806 Returns: 

807 The generated report. 

808 

809 """ 

810 raise NotImplementedError 

811 

812 

813def _wrap_apply(method: Callable[..., Any]) -> Callable[..., Any]: 

814 """Returns `method` wrapped so that calls to it go through `_call_apply`. 

815 

816 A call is only passed to `_call_apply` if `method` is the `apply` of the 

817 vertex's own class. Otherwise, it was called through `super()` by the 

818 `apply` of a subclass (which already went through `_call_apply`), so it is 

819 passed straight to `method`. 

820 

821 Args: 

822 method: the `apply` method of a `Vertex` subclass. 

823 

824 Returns: 

825 The wrapped method. 

826 

827 """ 

828 

829 @functools.wraps(method) 

830 def apply(self: Vertex, item: Any, **kwargs: Any) -> Any: 

831 if type(self).apply is not apply: 

832 return method(self, item, **kwargs) 

833 return self._call_apply(method, item, **kwargs) 

834 

835 setattr(apply, _WRAPPED, True) 

836 return apply