2022-01-24 04:07:52 +00:00
|
|
|
"""Object representations for debugging purposes. Unlike the default
|
|
|
|
repr, these expose more information and produce HTML instead of ASCII.
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
Together with the CSS and JavaScript of the debugger this gives a
|
|
|
|
colorful and more compact output.
|
2019-12-02 21:46:54 +00:00
|
|
|
"""
|
2024-03-03 17:15:23 +00:00
|
|
|
from __future__ import annotations
|
|
|
|
|
2019-12-02 21:46:54 +00:00
|
|
|
import codecs
|
|
|
|
import re
|
|
|
|
import sys
|
2022-01-24 04:07:52 +00:00
|
|
|
import typing as t
|
2019-12-02 21:46:54 +00:00
|
|
|
from collections import deque
|
|
|
|
from traceback import format_exception_only
|
|
|
|
|
2022-11-07 18:06:49 +00:00
|
|
|
from markupsafe import escape
|
|
|
|
|
2019-12-02 21:46:54 +00:00
|
|
|
missing = object()
|
|
|
|
_paragraph_re = re.compile(r"(?:\r\n|\r|\n){2,}")
|
|
|
|
RegexType = type(_paragraph_re)
|
|
|
|
|
|
|
|
HELP_HTML = """\
|
|
|
|
<div class=box>
|
|
|
|
<h3>%(title)s</h3>
|
|
|
|
<pre class=help>%(text)s</pre>
|
|
|
|
</div>\
|
|
|
|
"""
|
|
|
|
OBJECT_DUMP_HTML = """\
|
|
|
|
<div class=box>
|
|
|
|
<h3>%(title)s</h3>
|
|
|
|
%(repr)s
|
|
|
|
<table>%(items)s</table>
|
|
|
|
</div>\
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def debug_repr(obj: object) -> str:
|
|
|
|
"""Creates a debug repr of an object as HTML string."""
|
2019-12-02 21:46:54 +00:00
|
|
|
return DebugReprGenerator().repr(obj)
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def dump(obj: object = missing) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Print the object details to stdout._write (for the interactive
|
|
|
|
console of the web debugger.
|
|
|
|
"""
|
|
|
|
gen = DebugReprGenerator()
|
|
|
|
if obj is missing:
|
|
|
|
rv = gen.dump_locals(sys._getframe(1).f_locals)
|
|
|
|
else:
|
|
|
|
rv = gen.dump_object(obj)
|
2022-01-24 04:07:52 +00:00
|
|
|
sys.stdout._write(rv) # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
class _Helper:
|
2019-12-02 21:46:54 +00:00
|
|
|
"""Displays an HTML version of the normal help, for the interactive
|
|
|
|
debugger only because it requires a patched sys.stdout.
|
|
|
|
"""
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def __repr__(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
return "Type help(object) for help about object."
|
|
|
|
|
2024-03-03 17:15:23 +00:00
|
|
|
def __call__(self, topic: t.Any | None = None) -> None:
|
2019-12-02 21:46:54 +00:00
|
|
|
if topic is None:
|
2022-01-24 04:07:52 +00:00
|
|
|
sys.stdout._write(f"<span class=help>{self!r}</span>") # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
return
|
|
|
|
import pydoc
|
|
|
|
|
|
|
|
pydoc.help(topic)
|
2022-01-24 04:07:52 +00:00
|
|
|
rv = sys.stdout.reset() # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
paragraphs = _paragraph_re.split(rv)
|
|
|
|
if len(paragraphs) > 1:
|
|
|
|
title = paragraphs[0]
|
|
|
|
text = "\n\n".join(paragraphs[1:])
|
2022-01-24 04:07:52 +00:00
|
|
|
else:
|
2019-12-02 21:46:54 +00:00
|
|
|
title = "Help"
|
|
|
|
text = paragraphs[0]
|
2022-01-24 04:07:52 +00:00
|
|
|
sys.stdout._write(HELP_HTML % {"title": title, "text": text}) # type: ignore
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
|
|
|
|
helper = _Helper()
|
|
|
|
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def _add_subclass_info(
|
2024-03-03 17:15:23 +00:00
|
|
|
inner: str, obj: object, base: t.Type | tuple[t.Type, ...]
|
2022-01-24 04:07:52 +00:00
|
|
|
) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
if isinstance(base, tuple):
|
2022-11-07 18:06:49 +00:00
|
|
|
for cls in base:
|
|
|
|
if type(obj) is cls:
|
2019-12-02 21:46:54 +00:00
|
|
|
return inner
|
|
|
|
elif type(obj) is base:
|
|
|
|
return inner
|
|
|
|
module = ""
|
|
|
|
if obj.__class__.__module__ not in ("__builtin__", "exceptions"):
|
2022-01-24 04:07:52 +00:00
|
|
|
module = f'<span class="module">{obj.__class__.__module__}.</span>'
|
|
|
|
return f"{module}{type(obj).__name__}({inner})"
|
|
|
|
|
|
|
|
|
|
|
|
def _sequence_repr_maker(
|
|
|
|
left: str, right: str, base: t.Type, limit: int = 8
|
2024-03-03 17:15:23 +00:00
|
|
|
) -> t.Callable[[DebugReprGenerator, t.Iterable, bool], str]:
|
|
|
|
def proxy(self: DebugReprGenerator, obj: t.Iterable, recursive: bool) -> str:
|
2022-01-24 04:07:52 +00:00
|
|
|
if recursive:
|
|
|
|
return _add_subclass_info(f"{left}...{right}", obj, base)
|
|
|
|
buf = [left]
|
|
|
|
have_extended_section = False
|
|
|
|
for idx, item in enumerate(obj):
|
|
|
|
if idx:
|
|
|
|
buf.append(", ")
|
|
|
|
if idx == limit:
|
|
|
|
buf.append('<span class="extended">')
|
|
|
|
have_extended_section = True
|
|
|
|
buf.append(self.repr(item))
|
|
|
|
if have_extended_section:
|
|
|
|
buf.append("</span>")
|
|
|
|
buf.append(right)
|
|
|
|
return _add_subclass_info("".join(buf), obj, base)
|
|
|
|
|
|
|
|
return proxy
|
|
|
|
|
|
|
|
|
|
|
|
class DebugReprGenerator:
|
|
|
|
def __init__(self) -> None:
|
2024-03-03 17:15:23 +00:00
|
|
|
self._stack: list[t.Any] = []
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
list_repr = _sequence_repr_maker("[", "]", list)
|
|
|
|
tuple_repr = _sequence_repr_maker("(", ")", tuple)
|
|
|
|
set_repr = _sequence_repr_maker("set([", "])", set)
|
|
|
|
frozenset_repr = _sequence_repr_maker("frozenset([", "])", frozenset)
|
|
|
|
deque_repr = _sequence_repr_maker(
|
2022-01-24 04:07:52 +00:00
|
|
|
'<span class="module">collections.</span>deque([', "])", deque
|
2019-12-02 21:46:54 +00:00
|
|
|
)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def regex_repr(self, obj: t.Pattern) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
pattern = repr(obj.pattern)
|
2024-03-03 17:15:23 +00:00
|
|
|
pattern = codecs.decode(pattern, "unicode-escape", "ignore")
|
2022-01-24 04:07:52 +00:00
|
|
|
pattern = f"r{pattern}"
|
|
|
|
return f're.compile(<span class="string regex">{pattern}</span>)'
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2024-03-03 17:15:23 +00:00
|
|
|
def string_repr(self, obj: str | bytes, limit: int = 70) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
buf = ['<span class="string">']
|
|
|
|
r = repr(obj)
|
|
|
|
|
|
|
|
# shorten the repr when the hidden part would be at least 3 chars
|
|
|
|
if len(r) - limit > 2:
|
|
|
|
buf.extend(
|
|
|
|
(
|
|
|
|
escape(r[:limit]),
|
|
|
|
'<span class="extended">',
|
|
|
|
escape(r[limit:]),
|
|
|
|
"</span>",
|
|
|
|
)
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
buf.append(escape(r))
|
|
|
|
|
|
|
|
buf.append("</span>")
|
2022-01-24 04:07:52 +00:00
|
|
|
out = "".join(buf)
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
# if the repr looks like a standard string, add subclass info if needed
|
2022-01-24 04:07:52 +00:00
|
|
|
if r[0] in "'\"" or (r[0] == "b" and r[1] in "'\""):
|
|
|
|
return _add_subclass_info(out, obj, (bytes, str))
|
2019-12-02 21:46:54 +00:00
|
|
|
|
|
|
|
# otherwise, assume the repr distinguishes the subclass already
|
|
|
|
return out
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def dict_repr(
|
|
|
|
self,
|
2024-03-03 17:15:23 +00:00
|
|
|
d: dict[int, None] | dict[str, int] | dict[str | int, int],
|
2022-01-24 04:07:52 +00:00
|
|
|
recursive: bool,
|
|
|
|
limit: int = 5,
|
|
|
|
) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
if recursive:
|
2022-01-24 04:07:52 +00:00
|
|
|
return _add_subclass_info("{...}", d, dict)
|
2019-12-02 21:46:54 +00:00
|
|
|
buf = ["{"]
|
|
|
|
have_extended_section = False
|
2022-01-24 04:07:52 +00:00
|
|
|
for idx, (key, value) in enumerate(d.items()):
|
2019-12-02 21:46:54 +00:00
|
|
|
if idx:
|
|
|
|
buf.append(", ")
|
|
|
|
if idx == limit - 1:
|
|
|
|
buf.append('<span class="extended">')
|
|
|
|
have_extended_section = True
|
|
|
|
buf.append(
|
2022-01-24 04:07:52 +00:00
|
|
|
f'<span class="pair"><span class="key">{self.repr(key)}</span>:'
|
|
|
|
f' <span class="value">{self.repr(value)}</span></span>'
|
2019-12-02 21:46:54 +00:00
|
|
|
)
|
|
|
|
if have_extended_section:
|
|
|
|
buf.append("</span>")
|
|
|
|
buf.append("}")
|
2022-01-24 04:07:52 +00:00
|
|
|
return _add_subclass_info("".join(buf), d, dict)
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2024-03-03 17:15:23 +00:00
|
|
|
def object_repr(self, obj: type[dict] | t.Callable | type[list] | None) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
r = repr(obj)
|
2022-01-24 04:07:52 +00:00
|
|
|
return f'<span class="object">{escape(r)}</span>'
|
2019-12-02 21:46:54 +00:00
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def dispatch_repr(self, obj: t.Any, recursive: bool) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
if obj is helper:
|
2022-01-24 04:07:52 +00:00
|
|
|
return f'<span class="help">{helper!r}</span>'
|
|
|
|
if isinstance(obj, (int, float, complex)):
|
|
|
|
return f'<span class="number">{obj!r}</span>'
|
|
|
|
if isinstance(obj, str) or isinstance(obj, bytes):
|
2019-12-02 21:46:54 +00:00
|
|
|
return self.string_repr(obj)
|
|
|
|
if isinstance(obj, RegexType):
|
|
|
|
return self.regex_repr(obj)
|
|
|
|
if isinstance(obj, list):
|
|
|
|
return self.list_repr(obj, recursive)
|
|
|
|
if isinstance(obj, tuple):
|
|
|
|
return self.tuple_repr(obj, recursive)
|
|
|
|
if isinstance(obj, set):
|
|
|
|
return self.set_repr(obj, recursive)
|
|
|
|
if isinstance(obj, frozenset):
|
|
|
|
return self.frozenset_repr(obj, recursive)
|
|
|
|
if isinstance(obj, dict):
|
|
|
|
return self.dict_repr(obj, recursive)
|
2022-01-24 04:07:52 +00:00
|
|
|
if isinstance(obj, deque):
|
2019-12-02 21:46:54 +00:00
|
|
|
return self.deque_repr(obj, recursive)
|
|
|
|
return self.object_repr(obj)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def fallback_repr(self) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
try:
|
|
|
|
info = "".join(format_exception_only(*sys.exc_info()[:2]))
|
2022-01-24 04:07:52 +00:00
|
|
|
except Exception:
|
2019-12-02 21:46:54 +00:00
|
|
|
info = "?"
|
2022-01-24 04:07:52 +00:00
|
|
|
return (
|
|
|
|
'<span class="brokenrepr">'
|
|
|
|
f"<broken repr ({escape(info.strip())})></span>"
|
2019-12-02 21:46:54 +00:00
|
|
|
)
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def repr(self, obj: object) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
recursive = False
|
|
|
|
for item in self._stack:
|
|
|
|
if item is obj:
|
|
|
|
recursive = True
|
|
|
|
break
|
|
|
|
self._stack.append(obj)
|
|
|
|
try:
|
|
|
|
try:
|
|
|
|
return self.dispatch_repr(obj, recursive)
|
|
|
|
except Exception:
|
|
|
|
return self.fallback_repr()
|
|
|
|
finally:
|
|
|
|
self._stack.pop()
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def dump_object(self, obj: object) -> str:
|
|
|
|
repr = None
|
2024-03-03 17:15:23 +00:00
|
|
|
items: list[tuple[str, str]] | None = None
|
2022-01-24 04:07:52 +00:00
|
|
|
|
2019-12-02 21:46:54 +00:00
|
|
|
if isinstance(obj, dict):
|
|
|
|
title = "Contents of"
|
|
|
|
items = []
|
2022-01-24 04:07:52 +00:00
|
|
|
for key, value in obj.items():
|
|
|
|
if not isinstance(key, str):
|
2019-12-02 21:46:54 +00:00
|
|
|
items = None
|
|
|
|
break
|
|
|
|
items.append((key, self.repr(value)))
|
|
|
|
if items is None:
|
|
|
|
items = []
|
|
|
|
repr = self.repr(obj)
|
|
|
|
for key in dir(obj):
|
|
|
|
try:
|
|
|
|
items.append((key, self.repr(getattr(obj, key))))
|
|
|
|
except Exception:
|
|
|
|
pass
|
|
|
|
title = "Details for"
|
2022-01-24 04:07:52 +00:00
|
|
|
title += f" {object.__repr__(obj)[1:-1]}"
|
2019-12-02 21:46:54 +00:00
|
|
|
return self.render_object_dump(items, title, repr)
|
|
|
|
|
2024-03-03 17:15:23 +00:00
|
|
|
def dump_locals(self, d: dict[str, t.Any]) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
items = [(key, self.repr(value)) for key, value in d.items()]
|
|
|
|
return self.render_object_dump(items, "Local variables in frame")
|
|
|
|
|
2022-01-24 04:07:52 +00:00
|
|
|
def render_object_dump(
|
2024-03-03 17:15:23 +00:00
|
|
|
self, items: list[tuple[str, str]], title: str, repr: str | None = None
|
2022-01-24 04:07:52 +00:00
|
|
|
) -> str:
|
2019-12-02 21:46:54 +00:00
|
|
|
html_items = []
|
|
|
|
for key, value in items:
|
2022-01-24 04:07:52 +00:00
|
|
|
html_items.append(f"<tr><th>{escape(key)}<td><pre class=repr>{value}</pre>")
|
2019-12-02 21:46:54 +00:00
|
|
|
if not html_items:
|
|
|
|
html_items.append("<tr><td><em>Nothing</em>")
|
|
|
|
return OBJECT_DUMP_HTML % {
|
|
|
|
"title": escape(title),
|
2022-01-24 04:07:52 +00:00
|
|
|
"repr": f"<pre class=repr>{repr if repr else ''}</pre>",
|
2019-12-02 21:46:54 +00:00
|
|
|
"items": "\n".join(html_items),
|
|
|
|
}
|