msgspec
msgspec copied to clipboard
feat: add `repr` kwarg to `field` function and `Field` C struct
I picked up ticket #492 to help contribute this feature, as I'd really like to use this library for a project which requires excluding fields (a linked list with mutual references which would produce infinite loop if repr'd).
To begin, I have done the following:
- Extended the field Python function to accept a new keyword argument
reprwhich controls the inclusion of the field in the generated__repr__string for the struct. - Added a new attribute
reprto theFieldC struct to store the value of thereprkeyword argument. - Updated the
FieldC struct docstring to include details about the newreprkwarg.
Then to complete the feature I followed the lead of the other lookup dictionaries (ending in _lk) like defaults_lk, and used a list that was converted to a tuple, as I'm sure you're familiar. For boolean configuration I have only allowed this to be Py_True or Py_False, and defaulting to Py_True if the value type is not a Field object. With a little extra logic here this could be extended to handle arbitary callables if desired.
I tried to follow the example of how to represent repr in C from where other arguments use int to represent booleans. Please take a careful look at this to ensure it fits the house style.
>>> class A(msgspec.Struct):
... a: int = msgspec.field(repr=False)
... b: int
...
>>> A(a=1, b=2)
A(b=2)
Update I've added tests and remembered to also implement this feature in the __rich_repr__ method internal too.
Update I've implemented support for callables as described in the original ticket
Update I reviewed the memory management (incrementing/decrementing), refcount tests continue to pass
I've implemented support for callable arguments and added all the test coverage I think this feature needs now, looks ready to review @jcrist :tada: Please let me know of any changes you'd like me to make
This would be super valuable for e.g. not accidentally exposing secrets in logs.