Skip to content

Commit 6edf293

Browse files
committed
Added DataclassPPrintMixin
1 parent bf3d148 commit 6edf293

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/sensai/util/string.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
11
import functools
22
import logging
3+
import pprint
34
import re
45
import sys
56
import types
67
from abc import ABC, abstractmethod
8+
from dataclasses import asdict, dataclass
79
from typing import Union, List, Dict, Any, Sequence, Iterable, Optional, Mapping, Callable
810

911
reCommaWhitespacePotentiallyBreaks = re.compile(r",\s+")
@@ -555,3 +557,35 @@ def with_break(self, n=1) -> "TextBuilder":
555557
for i in range(n):
556558
self._components.append("")
557559
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

Comments
 (0)