1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
|
#!/usr/bin/env python
# cython: language_level=3
#
# utils.py
"""
Functions and classes for pretty printing.
.. versionadded:: 0.10.0
"""
#
# Copyright © 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
#
# Based on CPython.
# Licensed under the Python Software Foundation License Version 2.
# Copyright © 2001-2020 Python Software Foundation. All rights reserved.
# Copyright © 2000 BeOpen.com. All rights reserved.
# Copyright © 1995-2000 Corporation for National Research Initiatives. All rights reserved.
# Copyright © 1991-1995 Stichting Mathematisch Centrum. All rights reserved.
#
# stdlib
import sys
from io import StringIO
from typing import IO, Any, Callable, Iterator, MutableMapping, Optional, Tuple, Type, TypeVar
try: # pragma: no cover
# 3rd party
from pprint36 import PrettyPrinter
from pprint36._pprint import _safe_key # type: ignore
supports_sort_dicts = True
except ImportError:
# stdlib
from pprint import PrettyPrinter, _safe_key # type: ignore
supports_sort_dicts = sys.version_info >= (3, 8)
__all__ = ["FancyPrinter", "simple_repr"]
_T = TypeVar("_T", bound=Type)
class FancyPrinter(PrettyPrinter):
"""
Subclass of :class:`~.pprint.PrettyPrinter` with different formatting.
:param indent: Number of spaces to indent for each level of nesting.
:param width: Attempted maximum number of columns in the output.
:param depth: The maximum depth to print out nested structures.
:param stream: The desired output stream. If omitted (or :py:obj:`False`), the standard
output stream available at construction will be used.
:param compact: If :py:obj:`True`, several items will be combined in one line.
:param sort_dicts: If :py:obj:`True`, dict keys are sorted.
Only takes effect on Python 3.8 and later,
or if `pprint36 <https://pypi.org/project/pprint36/>`_ is installed.
"""
def __init__(
self,
indent: int = 1,
width: int = 80,
depth: Optional[int] = None,
stream: Optional[IO[str]] = None,
*,
compact: bool = False,
sort_dicts: bool = True,
):
if supports_sort_dicts:
super().__init__(
indent=indent,
width=width,
depth=depth,
stream=stream,
compact=compact,
sort_dicts=sort_dicts,
)
else:
super().__init__(
indent=indent,
width=width,
depth=depth,
stream=stream,
compact=compact,
)
_dispatch: MutableMapping[Callable, Callable]
_indent_per_level: int
_format_items: Callable[[PrettyPrinter, Any, Any, Any, Any, Any, Any], None]
_dispatch = dict(PrettyPrinter._dispatch) # type: ignore
def _make_open(self, char: str, indent: int, obj):
if self._indent_per_level > 1:
the_indent = ' ' * (indent + 1)
else:
the_indent = ' ' * (indent + self._indent_per_level)
if obj and not self._compact: # type: ignore
return f"{char}\n{the_indent}"
else:
return char
def _make_close(self, char: str, indent: int, obj):
if obj and not self._compact: # type: ignore
return f",\n{' ' * (indent + self._indent_per_level)}{char}"
else:
return char
def _pprint_dict(
self,
object, # noqa: A002 # pylint: disable=redefined-builtin
stream,
indent,
allowance,
context,
level,
):
obj = object
write = stream.write
write(self._make_open('{', indent, obj))
if self._indent_per_level > 1:
write((self._indent_per_level - 1) * ' ')
if obj:
self._format_dict_items( # type: ignore
obj.items(),
stream,
indent,
allowance + 1,
context,
level,
)
write(self._make_close('}', indent, obj))
_dispatch[dict.__repr__] = _pprint_dict
def _pprint_list(self, obj, stream, indent, allowance, context, level):
stream.write(self._make_open('[', indent, obj))
self._format_items(obj, stream, indent, allowance + 1, context, level)
stream.write(self._make_close(']', indent, obj))
_dispatch[list.__repr__] = _pprint_list
def _pprint_tuple(self, obj, stream, indent, allowance, context, level):
stream.write(self._make_open('(', indent, obj))
endchar = ",)" if len(obj) == 1 else self._make_close(')', indent, obj)
self._format_items(obj, stream, indent, allowance + len(endchar), context, level)
stream.write(endchar)
_dispatch[tuple.__repr__] = _pprint_tuple
def _pprint_set(self, obj, stream, indent, allowance, context, level):
if not obj:
stream.write(repr(obj))
return
typ = obj.__class__
if typ is set:
stream.write(self._make_open('{', indent, obj))
endchar = self._make_close('}', indent, obj)
else:
stream.write(typ.__name__ + f"({{\n{' ' * (indent + self._indent_per_level + len(typ.__name__) + 1)}")
endchar = f",\n{' ' * (indent + self._indent_per_level + len(typ.__name__) + 1)}}})"
indent += len(typ.__name__) + 1
obj = sorted(obj, key=_safe_key)
self._format_items(obj, stream, indent, allowance + len(endchar), context, level)
stream.write(endchar)
_dispatch[set.__repr__] = _pprint_set
_dispatch[frozenset.__repr__] = _pprint_set
class Attributes:
def __init__(self, obj: object, *attributes: str):
self.obj = obj
self.attributes = attributes
def __iter__(self) -> Iterator[Tuple[str, Any]]:
for attr in self.attributes:
yield attr, getattr(self.obj, attr)
def __len__(self) -> int:
return len(self.attributes)
def __repr__(self) -> str:
return f"Attributes{self.attributes}"
class ReprPrettyPrinter(FancyPrinter):
_dispatch = dict(FancyPrinter._dispatch)
def format_attributes(self, obj: Attributes):
stream = StringIO()
context = {}
context[id(obj)] = 1
stream.write(f"(\n{self._indent_per_level * ' '}")
if self._indent_per_level > 1:
stream.write((self._indent_per_level - 1) * ' ')
if obj:
self._format_attribute_items(list(obj), stream, 0, 0 + 1, context, 1)
stream.write(f"\n{self._indent_per_level * ' '})")
del context[id(obj)]
return stream.getvalue()
def _format_attribute_items(self, items, stream, indent, allowance, context, level):
write = stream.write
indent += self._indent_per_level
delimnl = ",\n" + ' ' * indent
last_index = len(items) - 1
for i, (key, ent) in enumerate(items):
last = i == last_index
write(key)
write('=')
self._format( # type: ignore
ent,
stream,
indent + len(key) + 2,
allowance if last else 1,
context,
level,
)
if not last:
write(delimnl)
_default_formatter = ReprPrettyPrinter()
def simple_repr(*attributes: str, show_module: bool = False, **kwargs):
r"""
Adds a simple ``__repr__`` method to the decorated class.
:param attributes: The attributes to include in the ``__repr__``.
:param show_module: Whether to show the name of the module in the ``__repr__``.
:param \*\*kwargs: Keyword arguments passed on to :class:`pprint.PrettyPrinter`.
"""
def deco(obj: _T) -> _T:
def __repr__(self) -> str:
if kwargs:
formatter = ReprPrettyPrinter(**kwargs)
else:
formatter = _default_formatter
class_name = f"{type(self).__module__}.{type(self).__name__}" if show_module else type(self).__name__
return f"{class_name}{formatter.format_attributes(Attributes(self, *attributes))}"
__repr__.__doc__ = f"Return a string representation of the :class:`~{obj.__module__}.{obj.__name__}`."
__repr__.__name__ = "__repr__"
__repr__.__module__ = obj.__module__
__repr__.__qualname__ = f"{obj.__module__}.__repr__"
obj.__repr__ = __repr__ # type: ignore
return obj
return deco
|