[Tutor] Dataclass question

Albert-Jan Roskam sjeik_appie at hotmail.com
Fri Aug 23 11:53:46 EDT 2024


   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


More information about the Tutor mailing list