msgspec icon indicating copy to clipboard operation
msgspec copied to clipboard

feat: add `repr` kwarg to `field` function and `Field` C struct

Open lmmx opened this issue 2 years ago • 3 comments
trafficstars

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 repr which controls the inclusion of the field in the generated __repr__ string for the struct.
  • Added a new attribute repr to the Field C struct to store the value of the repr keyword argument.
  • Updated the Field C struct docstring to include details about the new repr kwarg.

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

lmmx avatar Sep 06 '23 22:09 lmmx

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

lmmx avatar Sep 08 '23 08:09 lmmx

This would be super valuable for e.g. not accidentally exposing secrets in logs.

dhirschfeld avatar May 01 '24 01:05 dhirschfeld