|
1 | 1 | import functools |
2 | 2 | import logging |
| 3 | +import pprint |
3 | 4 | import re |
4 | 5 | import sys |
5 | 6 | import types |
6 | 7 | from abc import ABC, abstractmethod |
| 8 | +from dataclasses import asdict, dataclass |
7 | 9 | from typing import Union, List, Dict, Any, Sequence, Iterable, Optional, Mapping, Callable |
8 | 10 |
|
9 | 11 | reCommaWhitespacePotentiallyBreaks = re.compile(r",\s+") |
@@ -555,3 +557,35 @@ def with_break(self, n=1) -> "TextBuilder": |
555 | 557 | for i in range(n): |
556 | 558 | self._components.append("") |
557 | 559 | return self |
| 560 | + |
| 561 | +@dataclass |
| 562 | +class DataclassPPrintMixin: |
| 563 | + """ |
| 564 | + This mixin provides methods for pretty-printing a dataclass as a dictionary, |
| 565 | + allowing the exclusion of specified fields when the print command is called. Useful for |
| 566 | + logging and debugging purposes where only certain fields of a dataclass should be displayed. |
| 567 | + It follows a different approach to the :class:`ToStringMixin` (which is not specialized for dataclasses), |
| 568 | + where the string representation is fixed and determined by the implementation. |
| 569 | + """ |
| 570 | + def pprint_asdict(self, exclude_fields: Optional[Sequence[str]] = None, indent: int = 4) -> None: |
| 571 | + """Pretty-print the object as a dict, excluding specified fields. |
| 572 | +
|
| 573 | + :param exclude_fields: A sequence of field names to exclude from the output. |
| 574 | + If None, no fields are excluded. |
| 575 | + :param indent: The indentation to use when pretty-printing. |
| 576 | + """ |
| 577 | + print(self.pprints_asdict(exclude_fields=exclude_fields, indent=indent)) |
| 578 | + |
| 579 | + def pprints_asdict(self, exclude_fields: Optional[Sequence[str]] = None, indent: int = 4) -> str: |
| 580 | + """String corresponding to pretty-print of the object as a dict, excluding specified fields. |
| 581 | +
|
| 582 | + :param exclude_fields: A sequence of field names to exclude from the output. |
| 583 | + If None, no fields are excluded. |
| 584 | + :param indent: The indentation to use when pretty-printing. |
| 585 | + """ |
| 586 | + prefix = f"{self.__class__.__name__}\n----------------------------------------\n" |
| 587 | + print_dict = asdict(self) |
| 588 | + exclude_fields = exclude_fields or [] |
| 589 | + for field in exclude_fields: |
| 590 | + print_dict.pop(field, None) |
| 591 | + return prefix + pprint.pformat(print_dict, indent=indent) |
0 commit comments