msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

Add support for repr customisation

Open aedify-swi opened this issue 2 years ago • 5 comments

Description

As mentioned in https://github.com/jcrist/msgspec/issues/491, it would be great to be able to change the repr of specific fields. Attrs does this.

I usually do this for sensitive fields or subclasses, where I want to reduce the print output (e.g. I am only interested in a field of that subclass for logging).

I'd suggest adding this to Meta:


Password = Annotated[str, msgspec.Meta(repr=lambda x: "***")]

class Credentials(msgspec.Struct):
    user: str
    password: Password

print(Credentials("Jim", "secret"))
# Credentals(user="Jim", password="***")

What do you think?

aedify-swi avatar Jul 26 '23 06:07 aedify-swi

I think this could be in scope. I already had plans to support excluding fields from a repr, from looking at the attrs docs they also support passing a callable to repr to override how a field is repr'd. Seems like a natural extension.

The api would be as follows:

class Example(msgspec.Struct):
    x: int   # always repr'd like normal
    y: int = msgspec.field(repr=False)  # excluded from the repr
    z: int = msgspec.field(repr=hex)  # uses the passed callable to repr the field

jcrist avatar Jul 26 '23 13:07 jcrist

That's great :)

aedify-swi avatar Jul 26 '23 13:07 aedify-swi

Hello, I just found this library which I plan to use for a project, performances are great! However I was looking for a solution to exclude fields from the output, this solution would be perfect! Do you plan to add it in a future release please?

Julienh avatar Dec 23 '23 14:12 Julienh