msgspec
msgspec copied to clipboard
Add support for repr customisation
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?
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
That's great :)
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?