Skip to content

Commit

Permalink
feat(python): add pretty-printing of protobuf messages in IPython
Browse files Browse the repository at this point in the history
  • Loading branch information
dlitz authored and matejcik committed Oct 2, 2024
1 parent 774f9de commit 9416caa
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
1 change: 1 addition & 0 deletions python/.changelog.d/4076.added
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added pretty-printing of protobuf messages in IPython (`_repr_pretty_`)
36 changes: 36 additions & 0 deletions python/src/trezorlib/protobuf.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@

import typing_extensions as tx

if t.TYPE_CHECKING:
from IPython.lib.pretty import RepresentationPrinter # noqa: I900

T = t.TypeVar("T", bound=type)
MT = t.TypeVar("MT", bound="MessageType")

Expand Down Expand Up @@ -271,6 +274,39 @@ def __repr__(self) -> str:
d[key] = value
return f"<{self.__class__.__name__}: {d}>"

def _repr_pretty_(self, p: RepresentationPrinter, cycle: bool) -> None:
"""prettier version of __repr__ for IPython
This pretty-prints/indents the object when displayed in IPython,
for example:
<PrevInput: {'prev_hash': b'xyzasdf',
'prev_index': 1,
'script_sig': b'abcdef',
'sequence': 42,
'decred_tree': 21}>
The API is for this method is described in the IPython docs:
https://ipython.readthedocs.io/en/8.26.0/api/generated/IPython.lib.pretty.html
"""
prefix = f"<{self.__class__.__name__}: {{"
if cycle:
p.text(f"{prefix} ...>")
return
with p.group(len(prefix), prefix, f"}}>"): # noqa: F541
itemsiter = (
(key, value)
for key, value in self.__dict__.items()
if not (value is None or value == [])
)
for i, (key, value) in enumerate(itemsiter):
if i:
p.text(",")
p.breakable()
subprefix = f"{key!r}: "
with p.group(len(subprefix), subprefix, ""):
p.pretty(value)

def ByteSize(self) -> int:
data = BytesIO()
dump_message(data, self)
Expand Down

0 comments on commit 9416caa

Please sign in to comment.