Re: Dataclass question

Albert-Jan Roskam <[email protected]> Fri, 23 Aug 2024 18:04:22 +0200
Newsgroups gmane.comp.python.tutor
Message-ID <DB9PR10MB66891012318A94DFC941609983882@DB9PR10MB6689.EURPRD10.PROD.OUTLOOK.COM>
   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 <[email protected]> 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  -  [email protected]
     To unsubscribe or change subscription options:
     https://mail.python.org/mailman/listinfo/tutor
_______________________________________________
Tutor maillist  -  [email protected]
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor