From 8f40e522efcb134a32a1fe42920c5e7d6c679d85 Mon Sep 17 00:00:00 2001 From: Tyler Goodlet Date: Mon, 10 Jul 2023 09:28:38 -0400 Subject: [PATCH] Add handy `DiffDump`ing for our `.types.Struct` So you can do a `Struct1` - `Struct2` and we dump a little diff `list` of tuples for anal on the REPL B) Prolly can be broken out into it's own micro-patch? --- piker/data/types.py | 57 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 56 insertions(+), 1 deletion(-) diff --git a/piker/data/types.py b/piker/data/types.py index 596195cc..c5591500 100644 --- a/piker/data/types.py +++ b/piker/data/types.py @@ -21,7 +21,11 @@ Extensions to built-in or (heavily used but 3rd party) friend-lib types. ''' -from pprint import pformat +from collections import UserList +from pprint import ( + pformat, +) +from typing import Any from msgspec import ( msgpack, @@ -30,6 +34,33 @@ from msgspec import ( ) +class DiffDump(UserList): + ''' + Very simple list delegator that repr() dumps (presumed) tuple + elements of the form `tuple[str, Any, Any]` in a nice + multi-line readable form for analyzing `Struct` diffs. + + ''' + def __repr__(self) -> str: + if not len(self): + return super().__repr__() + + # format by displaying item pair's ``repr()`` on multiple, + # indented lines such that they are more easily visually + # comparable when printed to console when printed to + # console. + repstr: str = '[\n' + for k, left, right in self: + repstr += ( + f'({k},\n' + f'\t{repr(left)},\n' + f'\t{repr(right)},\n' + ')\n' + ) + repstr += ']\n' + return repstr + + class Struct( Struct, @@ -102,3 +133,27 @@ class Struct( fi.name, fi.type(getattr(self, fi.name)), ) + + def __sub__( + self, + other: Struct, + + ) -> DiffDump[tuple[str, Any, Any]]: + ''' + Compare fields/items key-wise and return a ``DiffDump`` + for easy visual REPL comparison B) + + ''' + diffs: DiffDump[tuple[str, Any, Any]] = DiffDump() + for fi in structs.fields(self): + attr_name: str = fi.name + ours: Any = getattr(self, attr_name) + theirs: Any = getattr(other, attr_name) + if ours != theirs: + diffs.append(( + attr_name, + ours, + theirs, + )) + + return diffs