Debian Codegraph @

src/_pytest/_io/pprint.py

raw
1 # mypy: allow-untyped-defs
2 # This module was imported from the cpython standard library
3 # (https://github.com/python/cpython/) at commit
4 # c5140945c723ae6c4b7ee81ff720ac8ea4b52cfd (python3.12).
5 #
6 #
7 # Original Author: Fred L. Drake, Jr.
8 # [email protected]
9 #
10 # This is a simple little module I wrote to make life easier. I didn't
11 # see anything quite like it in the library, though I may have overlooked
12 # something. I wrote this when I was trying to read some heavily nested
13 # tuples with fairly non-descriptive content. This is modeled very much
14 # after Lisp/Scheme - style pretty-printing of lists. If you find it
15 # useful, thank small children who sleep at night.
16 from __future__ import annotations
17
18 import collections as _collections
19 from collections.abc import Callable
20 from collections.abc import Iterator
21 import dataclasses as _dataclasses
22 from io import StringIO as _StringIO
23 import re
24 import types as _types
25 from typing import Any
26 from typing import IO
27
28
29 class _safe_key:
30 """Helper function for key functions when sorting unorderable objects.
31
32 The wrapped-object will fallback to a Py2.x style comparison for
33 unorderable types (sorting first comparing the type name and then by
34 the obj ids). Does not work recursively, so dict.items() must have
35 _safe_key applied to both the key and the value.
36
37 """
38
39 __slots__ = ["obj"]
40
41 def __init__(self, obj):
42 self.obj = obj
43
44 def __lt__(self, other):
45 try:
46 return self.obj < other.obj
47 except TypeError:
48 return (str(type(self.obj)), id(self.obj)) < (
49 str(type(other.obj)),
50 id(other.obj),
51 )
52
53
54 def _safe_tuple(t):
55 """Helper function for comparing 2-tuples"""
56 return _safe_key(t[0]), _safe_key(t[1])
57
58
59 class PrettyPrinter:
60 def __init__(
61 self,
62 indent: int = 4,
63 width: int = 80,
64 depth: int | None = None,
65 ) -> None:
66 """Handle pretty printing operations onto a stream using a set of
67 configured parameters.
68
69 indent
70 Number of spaces to indent for each level of nesting.
71
72 width
73 Attempted maximum number of columns in the output.
74
75 depth
76 The maximum depth to print out nested structures.
77
78 """
79 if indent < 0:
80 raise ValueError("indent must be >= 0")
81 if depth is not None and depth <= 0:
82 raise ValueError("depth must be > 0")
83 if not width:
84 raise ValueError("width must be != 0")
85 self._depth = depth
86 self._indent_per_level = indent
87 self._width = width
88
89 def pformat(self, object: Any) -> str:
90 sio = _StringIO()
91 self._format(object, sio, 0, 0, set(), 0)
92 return sio.getvalue()
93
94 def _format(
95 self,
96 object: Any,
97 stream: IO[str],
98 indent: int,
99 allowance: int,
100 context: set[int],
101 level: int,
102 ) -> None:
103 objid = id(object)
104 if objid in context:
105 stream.write(_recursion(object))
106 return
107
108 p = self._dispatch.get(type(object).__repr__, None)
109 if p is not None:
110 context.add(objid)
111 p(self, object, stream, indent, allowance, context, level + 1)
112 context.remove(objid)
113 elif (
114 _dataclasses.is_dataclass(object)
115 and not isinstance(object, type)
116 and object.__dataclass_params__.repr # type:ignore[attr-defined]
117 and
118 # Check dataclass has generated repr method.
119 hasattr(object.__repr__, "__wrapped__")
120 and "__create_fn__" in object.__repr__.__wrapped__.__qualname__
121 ):
122 context.add(objid)
123 self._pprint_dataclass(
124 object, stream, indent, allowance, context, level + 1
125 )
126 context.remove(objid)
127 else:
128 stream.write(self._repr(object, context, level))
129
130 def _pprint_dataclass(
131 self,
132 object: Any,
133 stream: IO[str],
134 indent: int,
135 allowance: int,
136 context: set[int],
137 level: int,
138 ) -> None:
139 cls_name = object.__class__.__name__
140 items = [
141 (f.name, getattr(object, f.name))
142 for f in _dataclasses.fields(object)
143 if f.repr
144 ]
145 stream.write(cls_name + "(")
146 self._format_namespace_items(items, stream, indent, allowance, context, level)
147 stream.write(")")
148
149 _dispatch: dict[
150 Callable[..., str],
151 Callable[[PrettyPrinter, Any, IO[str], int, int, set[int], int], None],
152 ] = {}
153
154 def _pprint_dict(
155 self,
156 object: Any,
157 stream: IO[str],
158 indent: int,
159 allowance: int,
160 context: set[int],
161 level: int,
162 ) -> None:
163 write = stream.write
164 write("{")
165 items = object.items()
166 self._format_dict_items(items, stream, indent, allowance, context, level)
167 write("}")
168
169 _dispatch[dict.__repr__] = _pprint_dict
170
171 def _pprint_ordered_dict(
172 self,
173 object: Any,
174 stream: IO[str],
175 indent: int,
176 allowance: int,
177 context: set[int],
178 level: int,
179 ) -> None:
180 if not len(object):
181 stream.write(repr(object))
182 return
183 cls = object.__class__
184 stream.write(cls.__name__ + "(")
185 self._pprint_dict(object, stream, indent, allowance, context, level)
186 stream.write(")")
187
188 _dispatch[_collections.OrderedDict.__repr__] = _pprint_ordered_dict
189
190 def _pprint_list(
191 self,
192 object: Any,
193 stream: IO[str],
194 indent: int,
195 allowance: int,
196 context: set[int],
197 level: int,
198 ) -> None:
199 stream.write("[")
200 self._format_items(object, stream, indent, allowance, context, level)
201 stream.write("]")
202
203 _dispatch[list.__repr__] = _pprint_list
204
205 def _pprint_tuple(
206 self,
207 object: Any,
208 stream: IO[str],
209 indent: int,
210 allowance: int,
211 context: set[int],
212 level: int,
213 ) -> None:
214 stream.write("(")
215 self._format_items(object, stream, indent, allowance, context, level)
216 stream.write(")")
217
218 _dispatch[tuple.__repr__] = _pprint_tuple
219
220 def _pprint_set(
221 self,
222 object: Any,
223 stream: IO[str],
224 indent: int,
225 allowance: int,
226 context: set[int],
227 level: int,
228 ) -> None:
229 if not len(object):
230 stream.write(repr(object))
231 return
232 typ = object.__class__
233 if typ is set:
234 stream.write("{")
235 endchar = "}"
236 else:
237 stream.write(typ.__name__ + "({")
238 endchar = "})"
239 object = sorted(object, key=_safe_key)
240 self._format_items(object, stream, indent, allowance, context, level)
241 stream.write(endchar)
242
243 _dispatch[set.__repr__] = _pprint_set
244 _dispatch[frozenset.__repr__] = _pprint_set
245
246 def _pprint_str(
247 self,
248 object: Any,
249 stream: IO[str],
250 indent: int,
251 allowance: int,
252 context: set[int],
253 level: int,
254 ) -> None:
255 write = stream.write
256 if not len(object):
257 write(repr(object))
258 return
259 chunks = []
260 lines = object.splitlines(True)
261 if level == 1:
262 indent += 1
263 allowance += 1
264 max_width1 = max_width = self._width - indent
265 for i, line in enumerate(lines):
266 rep = repr(line)
267 if i == len(lines) - 1:
268 max_width1 -= allowance
269 if len(rep) <= max_width1:
270 chunks.append(rep)
271 else:
272 # A list of alternating (non-space, space) strings
273 parts = re.findall(r"\S*\s*", line)
274 assert parts
275 assert not parts[-1]
276 parts.pop() # drop empty last part
277 max_width2 = max_width
278 current = ""
279 for j, part in enumerate(parts):
280 candidate = current + part
281 if j == len(parts) - 1 and i == len(lines) - 1:
282 max_width2 -= allowance
283 if len(repr(candidate)) > max_width2:
284 if current:
285 chunks.append(repr(current))
286 current = part
287 else:
288 current = candidate
289 if current:
290 chunks.append(repr(current))
291 if len(chunks) == 1:
292 write(rep)
293 return
294 if level == 1:
295 write("(")
296 for i, rep in enumerate(chunks):
297 if i > 0:
298 write("\n" + " " * indent)
299 write(rep)
300 if level == 1:
301 write(")")
302
303 _dispatch[str.__repr__] = _pprint_str
304
305 def _pprint_bytes(
306 self,
307 object: Any,
308 stream: IO[str],
309 indent: int,
310 allowance: int,
311 context: set[int],
312 level: int,
313 ) -> None:
314 write = stream.write
315 if len(object) <= 4:
316 write(repr(object))
317 return
318 parens = level == 1
319 if parens:
320 indent += 1
321 allowance += 1
322 write("(")
323 delim = ""
324 for rep in _wrap_bytes_repr(object, self._width - indent, allowance):
325 write(delim)
326 write(rep)
327 if not delim:
328 delim = "\n" + " " * indent
329 if parens:
330 write(")")
331
332 _dispatch[bytes.__repr__] = _pprint_bytes
333
334 def _pprint_bytearray(
335 self,
336 object: Any,
337 stream: IO[str],
338 indent: int,
339 allowance: int,
340 context: set[int],
341 level: int,
342 ) -> None:
343 write = stream.write
344 write("bytearray(")
345 self._pprint_bytes(
346 bytes(object), stream, indent + 10, allowance + 1, context, level + 1
347 )
348 write(")")
349
350 _dispatch[bytearray.__repr__] = _pprint_bytearray
351
352 def _pprint_mappingproxy(
353 self,
354 object: Any,
355 stream: IO[str],
356 indent: int,
357 allowance: int,
358 context: set[int],
359 level: int,
360 ) -> None:
361 stream.write("mappingproxy(")
362 self._format(object.copy(), stream, indent, allowance, context, level)
363 stream.write(")")
364
365 _dispatch[_types.MappingProxyType.__repr__] = _pprint_mappingproxy
366
367 def _pprint_simplenamespace(
368 self,
369 object: Any,
370 stream: IO[str],
371 indent: int,
372 allowance: int,
373 context: set[int],
374 level: int,
375 ) -> None:
376 if type(object) is _types.SimpleNamespace:
377 # The SimpleNamespace repr is "namespace" instead of the class
378 # name, so we do the same here. For subclasses; use the class name.
379 cls_name = "namespace"
380 else:
381 cls_name = object.__class__.__name__
382 items = object.__dict__.items()
383 stream.write(cls_name + "(")
384 self._format_namespace_items(items, stream, indent, allowance, context, level)
385 stream.write(")")
386
387 _dispatch[_types.SimpleNamespace.__repr__] = _pprint_simplenamespace
388
389 def _format_dict_items(
390 self,
391 items: list[tuple[Any, Any]],
392 stream: IO[str],
393 indent: int,
394 allowance: int,
395 context: set[int],
396 level: int,
397 ) -> None:
398 if not items:
399 return
400
401 write = stream.write
402 item_indent = indent + self._indent_per_level
403 delimnl = "\n" + " " * item_indent
404 for key, ent in items:
405 write(delimnl)
406 write(self._repr(key, context, level))
407 write(": ")
408 self._format(ent, stream, item_indent, 1, context, level)
409 write(",")
410
411 write("\n" + " " * indent)
412
413 def _format_namespace_items(
414 self,
415 items: list[tuple[Any, Any]],
416 stream: IO[str],
417 indent: int,
418 allowance: int,
419 context: set[int],
420 level: int,
421 ) -> None:
422 if not items:
423 return
424
425 write = stream.write
426 item_indent = indent + self._indent_per_level
427 delimnl = "\n" + " " * item_indent
428 for key, ent in items:
429 write(delimnl)
430 write(key)
431 write("=")
432 if id(ent) in context:
433 # Special-case representation of recursion to match standard
434 # recursive dataclass repr.
435 write("...")
436 else:
437 self._format(
438 ent,
439 stream,
440 item_indent + len(key) + 1,
441 1,
442 context,
443 level,
444 )
445
446 write(",")
447
448 write("\n" + " " * indent)
449
450 def _format_items(
451 self,
452 items: list[Any],
453 stream: IO[str],
454 indent: int,
455 allowance: int,
456 context: set[int],
457 level: int,
458 ) -> None:
459 if not items:
460 return
461
462 write = stream.write
463 item_indent = indent + self._indent_per_level
464 delimnl = "\n" + " " * item_indent
465
466 for item in items:
467 write(delimnl)
468 self._format(item, stream, item_indent, 1, context, level)
469 write(",")
470
471 write("\n" + " " * indent)
472
473 def _repr(self, object: Any, context: set[int], level: int) -> str:
474 return self._safe_repr(object, context.copy(), self._depth, level)
475
476 def _pprint_default_dict(
477 self,
478 object: Any,
479 stream: IO[str],
480 indent: int,
481 allowance: int,
482 context: set[int],
483 level: int,
484 ) -> None:
485 rdf = self._repr(object.default_factory, context, level)
486 stream.write(f"{object.__class__.__name__}({rdf}, ")
487 self._pprint_dict(object, stream, indent, allowance, context, level)
488 stream.write(")")
489
490 _dispatch[_collections.defaultdict.__repr__] = _pprint_default_dict
491
492 def _pprint_counter(
493 self,
494 object: Any,
495 stream: IO[str],
496 indent: int,
497 allowance: int,
498 context: set[int],
499 level: int,
500 ) -> None:
501 stream.write(object.__class__.__name__ + "(")
502
503 if object:
504 stream.write("{")
505 items = object.most_common()
506 self._format_dict_items(items, stream, indent, allowance, context, level)
507 stream.write("}")
508
509 stream.write(")")
510
511 _dispatch[_collections.Counter.__repr__] = _pprint_counter
512
513 def _pprint_chain_map(
514 self,
515 object: Any,
516 stream: IO[str],
517 indent: int,
518 allowance: int,
519 context: set[int],
520 level: int,
521 ) -> None:
522 if not len(object.maps) or (len(object.maps) == 1 and not len(object.maps[0])):
523 stream.write(repr(object))
524 return
525
526 stream.write(object.__class__.__name__ + "(")
527 self._format_items(object.maps, stream, indent, allowance, context, level)
528 stream.write(")")
529
530 _dispatch[_collections.ChainMap.__repr__] = _pprint_chain_map
531
532 def _pprint_deque(
533 self,
534 object: Any,
535 stream: IO[str],
536 indent: int,
537 allowance: int,
538 context: set[int],
539 level: int,
540 ) -> None:
541 stream.write(object.__class__.__name__ + "(")
542 if object.maxlen is not None:
543 stream.write(f"maxlen={object.maxlen}, ")
544 stream.write("[")
545
546 self._format_items(object, stream, indent, allowance + 1, context, level)
547 stream.write("])")
548
549 _dispatch[_collections.deque.__repr__] = _pprint_deque
550
551 def _pprint_user_dict(
552 self,
553 object: Any,
554 stream: IO[str],
555 indent: int,
556 allowance: int,
557 context: set[int],
558 level: int,
559 ) -> None:
560 self._format(object.data, stream, indent, allowance, context, level - 1)
561
562 _dispatch[_collections.UserDict.__repr__] = _pprint_user_dict
563
564 def _pprint_user_list(
565 self,
566 object: Any,
567 stream: IO[str],
568 indent: int,
569 allowance: int,
570 context: set[int],
571 level: int,
572 ) -> None:
573 self._format(object.data, stream, indent, allowance, context, level - 1)
574
575 _dispatch[_collections.UserList.__repr__] = _pprint_user_list
576
577 def _pprint_user_string(
578 self,
579 object: Any,
580 stream: IO[str],
581 indent: int,
582 allowance: int,
583 context: set[int],
584 level: int,
585 ) -> None:
586 self._format(object.data, stream, indent, allowance, context, level - 1)
587
588 _dispatch[_collections.UserString.__repr__] = _pprint_user_string
589
590 def _safe_repr(
591 self, object: Any, context: set[int], maxlevels: int | None, level: int
592 ) -> str:
593 typ = type(object)
594 if typ in _builtin_scalars:
595 return repr(object)
596
597 r = getattr(typ, "__repr__", None)
598
599 if issubclass(typ, dict) and r is dict.__repr__:
600 if not object:
601 return "{}"
602 objid = id(object)
603 if maxlevels and level >= maxlevels:
604 return "{...}"
605 if objid in context:
606 return _recursion(object)
607 context.add(objid)
608 components: list[str] = []
609 append = components.append
610 level += 1
611 for k, v in object.items():
612 krepr = self._safe_repr(k, context, maxlevels, level)
613 vrepr = self._safe_repr(v, context, maxlevels, level)
614 append(f"{krepr}: {vrepr}")
615 context.remove(objid)
616 return "{{{}}}".format(", ".join(components))
617
618 if (issubclass(typ, list) and r is list.__repr__) or (
619 issubclass(typ, tuple) and r is tuple.__repr__
620 ):
621 if issubclass(typ, list):
622 if not object:
623 return "[]"
624 format = "[%s]"
625 elif len(object) == 1:
626 format = "(%s,)"
627 else:
628 if not object:
629 return "()"
630 format = "(%s)"
631 objid = id(object)
632 if maxlevels and level >= maxlevels:
633 return format % "..."
634 if objid in context:
635 return _recursion(object)
636 context.add(objid)
637 components = []
638 append = components.append
639 level += 1
640 for o in object:
641 orepr = self._safe_repr(o, context, maxlevels, level)
642 append(orepr)
643 context.remove(objid)
644 return format % ", ".join(components)
645
646 return repr(object)
647
648
649 _builtin_scalars = frozenset(
650 {str, bytes, bytearray, float, complex, bool, type(None), int}
651 )
652
653
654 def _recursion(object: Any) -> str:
655 return f"<Recursion on {type(object).__name__} with id={id(object)}>"
656
657
658 def _wrap_bytes_repr(object: Any, width: int, allowance: int) -> Iterator[str]:
659 current = b""
660 last = len(object) // 4 * 4
661 for i in range(0, len(object), 4):
662 part = object[i : i + 4]
663 candidate = current + part
664 if i == last:
665 width -= allowance
666 if len(repr(candidate)) > width:
667 if current:
668 yield repr(current)
669 current = part
670 else:
671 current = candidate
672 if current:
673 yield repr(current)