[Tutor] Dataclass question
Albert-Jan Roskam
sjeik_appie at hotmail.com
Fri Aug 23 12:04:22 EDT 2024
Hmm, maybe ditch the AbbrevitatedBytes class and then:
def __post_init__(self):
self.z.__repr__ = lambda self, n=10: repr(self) if len(self) < n
else repr(self)[:n] + " [...]"
On Aug 23, 2024 17:53, Albert-Jan Roskam <sjeik_appie at hotmail.com> wrote:
Hi,
I'm using dataclasses and one of the fields is has a bytes type. It
could
be the contents of a .zip or .csv. I don't want to see so much
clutter in
the logs or on the screen, so I'm looking for a neat way to omit most
of
the info from the dataclass object's representation. Using the code
below,
field "y" is not shown at all, which is not really what I want (but
it's
nice and clean). Field "z" is more like it, but it requires more
code. Is
there a better way? Maybe with pydantic?
from dataclasses import field, dataclass
class AbbreviatedBytes(bytes):
def __repr__(self, width=2):
r = super().__repr__()
return r if len(self) < width else f"{r[:width + 1]} [...]'"
@dataclass
class Test:
x : bytes = b""
y : bytes = field(default=b"", repr=False)
z : bytes = b""
def __post_init__(self):
self.z = AbbreviatedBytes(self.z)
print(Test(b"aaaa", b"bbbb", b"cccc")) # output: Test(x=b'aaaa',
z=b'c
[...]')
Best wishes,
Albert-Jan
_______________________________________________
Tutor maillist - Tutor at python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list