[Tutor] Dataclass question
Mats Wichmann
mats at wichmann.us
Fri Aug 23 12:41:18 EDT 2024
On 8/23/24 09:53, Albert-Jan Roskam 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
This doesn't seem to have much to do with dataclasses. You're after a
string shortener to use in whatever repr method... are you just asking
about what convention to follow? Or for implementation?
Many shorteners (including the stdlib textwrap.shorten) drop chars from
the end and use a default placeholder of [...] (like your samples) but
take an optional placeholder argument. (textwrap would be no use to you
as it doesn't take bytes and only breaks on word boundaries - it's just
an illustration).
The unittest module also has a shortener it uses, which is a little more
general - it chops chars out from in between a prefix and suffix (you
can give the length of each) and inserts a counter of how much was
chopped in between, so you can get an output like:
prefixtext[13 characters]suffixtext
Frequently the placeholder for removed stuff is included in computing
the output size so if it's > SIZE and placeholder is 4 wide, you chop it
so the retained text is SIZE-4, and then append/insert the placeholder.
just some ideas to think about. You're just prettyfying stuff for
yourself, wouldn't worry about the "requires more code" aspect.
More information about the Tutor
mailing list