| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from itertools import islice |
| 4 |
import pprint |
| 5 |
import reprlib |
| 6 |
|
| 7 |
|
| 8 |
def _try_repr_or_str(obj: object) -> str: |
| 9 |
try: |
| 10 |
return repr(obj) |
| 11 |
except (KeyboardInterrupt, SystemExit): |
| 12 |
raise |
| 13 |
except BaseException: |
| 14 |
return f'{type(obj).__name__}("{obj}")' |
| 15 |
|
| 16 |
|
| 17 |
def _format_repr_exception(exc: BaseException, obj: object) -> str: |
| 18 |
try: |
| 19 |
exc_info = _try_repr_or_str(exc) |
| 20 |
except (KeyboardInterrupt, SystemExit): |
| 21 |
raise |
| 22 |
except BaseException as inner_exc: |
| 23 |
exc_info = f"unpresentable exception ({_try_repr_or_str(inner_exc)})" |
| 24 |
return ( |
| 25 |
f"<[{exc_info} raised in repr()] {type(obj).__name__} object at 0x{id(obj):x}>" |
| 26 |
) |
| 27 |
|
| 28 |
|
| 29 |
def _ellipsize(s: str, maxsize: int) -> str: |
| 30 |
if len(s) > maxsize: |
| 31 |
i = max(0, (maxsize - 3) // 2) |
| 32 |
j = max(0, maxsize - 3 - i) |
| 33 |
return s[:i] + "..." + s[len(s) - j :] |
| 34 |
return s |
| 35 |
|
| 36 |
|
| 37 |
class SafeRepr(reprlib.Repr): |
| 38 |
""" |
| 39 |
repr.Repr that limits the resulting size of repr() and includes |
| 40 |
information on exceptions raised during the call. |
| 41 |
""" |
| 42 |
|
| 43 |
def __init__(self, maxsize: int | None, use_ascii: bool = False) -> None: |
| 44 |
""" |
| 45 |
:param maxsize: |
| 46 |
If not None, will truncate the resulting repr to that specific size, using ellipsis |
| 47 |
somewhere in the middle to hide the extra text. |
| 48 |
If None, will not impose any size limits on the returning repr. |
| 49 |
""" |
| 50 |
super().__init__() |
| 51 |
# ``maxstring`` is used by the superclass, and needs to be an int; using a |
| 52 |
# very large number in case maxsize is None, meaning we want to disable |
| 53 |
# truncation. |
| 54 |
self.maxstring = maxsize if maxsize is not None else 1_000_000_000 |
| 55 |
self.maxsize = maxsize |
| 56 |
self.use_ascii = use_ascii |
| 57 |
|
| 58 |
def repr(self, x: object) -> str: |
| 59 |
try: |
| 60 |
if self.use_ascii: |
| 61 |
s = ascii(x) |
| 62 |
else: |
| 63 |
s = super().repr(x) |
| 64 |
except (KeyboardInterrupt, SystemExit): |
| 65 |
raise |
| 66 |
except BaseException as exc: |
| 67 |
s = _format_repr_exception(exc, x) |
| 68 |
if self.maxsize is not None: |
| 69 |
s = _ellipsize(s, self.maxsize) |
| 70 |
return s |
| 71 |
|
| 72 |
def repr_instance(self, x: object, level: int) -> str: |
| 73 |
try: |
| 74 |
s = repr(x) |
| 75 |
except (KeyboardInterrupt, SystemExit): |
| 76 |
raise |
| 77 |
except BaseException as exc: |
| 78 |
s = _format_repr_exception(exc, x) |
| 79 |
if self.maxsize is not None: |
| 80 |
s = _ellipsize(s, self.maxsize) |
| 81 |
|
| 82 |
return s |
| 83 |
|
| 84 |
def repr_dict(self, x: dict[object, object], level: int) -> str: |
| 85 |
"""Represent a dict while preserving its insertion order. |
| 86 |
|
| 87 |
Differs from ``reprlib.Repr.repr_dict`` by iterating directly over ``x`` |
| 88 |
rather than using the stdlib's sorting helper. |
| 89 |
""" |
| 90 |
fillvalue = "..." |
| 91 |
n = len(x) |
| 92 |
if n == 0: |
| 93 |
return "{}" |
| 94 |
if level <= 0: |
| 95 |
return "{" + fillvalue + "}" |
| 96 |
newlevel = level - 1 |
| 97 |
repr1 = self.repr1 |
| 98 |
pieces = [] |
| 99 |
for key in islice(x, self.maxdict): |
| 100 |
keyrepr = repr1(key, newlevel) |
| 101 |
valrepr = repr1(x[key], newlevel) |
| 102 |
pieces.append(f"{keyrepr}: {valrepr}") |
| 103 |
if n > self.maxdict: |
| 104 |
pieces.append(fillvalue) |
| 105 |
return "{" + ", ".join(pieces) + "}" |
| 106 |
|
| 107 |
|
| 108 |
def safeformat(obj: object) -> str: |
| 109 |
"""Return a pretty printed string for the given object. |
| 110 |
|
| 111 |
Failing __repr__ functions of user instances will be represented |
| 112 |
with a short exception info. |
| 113 |
""" |
| 114 |
try: |
| 115 |
return pprint.pformat(obj) |
| 116 |
except Exception as exc: |
| 117 |
return _format_repr_exception(exc, obj) |
| 118 |
|
| 119 |
|
| 120 |
# Maximum size of overall repr of objects to display during assertion errors. |
| 121 |
DEFAULT_REPR_MAX_SIZE = 240 |
| 122 |
|
| 123 |
|
| 124 |
def saferepr( |
| 125 |
obj: object, maxsize: int | None = DEFAULT_REPR_MAX_SIZE, use_ascii: bool = False |
| 126 |
) -> str: |
| 127 |
"""Return a size-limited safe repr-string for the given object. |
| 128 |
|
| 129 |
Failing __repr__ functions of user instances will be represented |
| 130 |
with a short exception info and 'saferepr' generally takes |
| 131 |
care to never raise exceptions itself. |
| 132 |
|
| 133 |
This function is a wrapper around the Repr/reprlib functionality of the |
| 134 |
stdlib. |
| 135 |
""" |
| 136 |
return SafeRepr(maxsize, use_ascii).repr(obj) |
| 137 |
|
| 138 |
|
| 139 |
def saferepr_unlimited(obj: object, use_ascii: bool = True) -> str: |
| 140 |
"""Return an unlimited-size safe repr-string for the given object. |
| 141 |
|
| 142 |
As with saferepr, failing __repr__ functions of user instances |
| 143 |
will be represented with a short exception info. |
| 144 |
|
| 145 |
This function is a wrapper around simple repr. |
| 146 |
|
| 147 |
Note: a cleaner solution would be to alter ``saferepr``this way |
| 148 |
when maxsize=None, but that might affect some other code. |
| 149 |
""" |
| 150 |
try: |
| 151 |
if use_ascii: |
| 152 |
return ascii(obj) |
| 153 |
return repr(obj) |
| 154 |
except Exception as exc: |
| 155 |
return _format_repr_exception(exc, obj) |