This function is the sanctioned way of converting objects to a string representation and properly handles nested sequences. Parameters ---------- thing : anything to be formatted _nest_lvl : internal use only. pprint_thing() is mutually-recursive with pprint_sequenc
(
thing: object,
_nest_lvl: int = 0,
escape_chars: EscapeChars | None = None,
default_escapes: bool = False,
quote_strings: bool = False,
max_seq_items: int | None = None,
)
| 172 | |
| 173 | |
| 174 | def pprint_thing( |
| 175 | thing: object, |
| 176 | _nest_lvl: int = 0, |
| 177 | escape_chars: EscapeChars | None = None, |
| 178 | default_escapes: bool = False, |
| 179 | quote_strings: bool = False, |
| 180 | max_seq_items: int | None = None, |
| 181 | ) -> str: |
| 182 | """ |
| 183 | This function is the sanctioned way of converting objects |
| 184 | to a string representation and properly handles nested sequences. |
| 185 | |
| 186 | Parameters |
| 187 | ---------- |
| 188 | thing : anything to be formatted |
| 189 | _nest_lvl : internal use only. pprint_thing() is mutually-recursive |
| 190 | with pprint_sequence, this argument is used to keep track of the |
| 191 | current nesting level, and limit it. |
| 192 | escape_chars : list[str] or Mapping[str, str], optional |
| 193 | Characters to escape. If a Mapping is passed the values are the |
| 194 | replacements |
| 195 | default_escapes : bool, default False |
| 196 | Whether the input escape characters replaces or adds to the defaults |
| 197 | max_seq_items : int or None, default None |
| 198 | Pass through to other pretty printers to limit sequence printing |
| 199 | |
| 200 | Returns |
| 201 | ------- |
| 202 | str |
| 203 | """ |
| 204 | |
| 205 | def as_escaped_string( |
| 206 | thing: Any, escape_chars: EscapeChars | None = escape_chars |
| 207 | ) -> str: |
| 208 | translate = {"\t": r"\t", "\n": r"\n", "\r": r"\r", "'": r"\'"} |
| 209 | if isinstance(escape_chars, Mapping): |
| 210 | if default_escapes: |
| 211 | translate.update(escape_chars) |
| 212 | else: |
| 213 | translate = escape_chars # type: ignore[assignment] |
| 214 | escape_chars = list(escape_chars.keys()) |
| 215 | else: |
| 216 | escape_chars = escape_chars or () |
| 217 | |
| 218 | result = str(thing) |
| 219 | for c in escape_chars: |
| 220 | result = result.replace(c, translate[c]) |
| 221 | return result |
| 222 | |
| 223 | if hasattr(thing, "__next__"): |
| 224 | return str(thing) |
| 225 | elif isinstance(thing, Mapping) and _nest_lvl < get_option( |
| 226 | "display.pprint_nest_depth" |
| 227 | ): |
| 228 | result = _pprint_dict( |
| 229 | thing, _nest_lvl, quote_strings=True, max_seq_items=max_seq_items |
| 230 | ) |
| 231 | elif is_sequence(thing) and _nest_lvl < get_option("display.pprint_nest_depth"): |