attrs icon indicating copy to clipboard operation
attrs copied to clipboard

Use field *repr* callable to dynamically define repr based on instance value

Open RNKuhns opened this issue 2 years ago • 4 comments

@hynek thanks for the work on attrs!

Ideally, I'd only like a field to appear in a class' repr if that field is set to a non-default value. An example of this approach is scikit-learn's approach to printing class representations.

I'm trying to understand if this is already possible currently in attrs. I know that attrs accepts a callable for the repr parameter of an attrs.field. But reading through the documentation, it is not clear what context (if any) is available to the repr. If the class' default values and the actual value of the parameter are as context to the callable, it would be relatively straightforward to craft a returned string that accomplished this.

Can you provide some info on what's available to the callable so I can understand if this is possible?

RNKuhns avatar Oct 18 '23 00:10 RNKuhns

Unfortunately, what you want it is currently not possible. The repr function only receives the value that's being repr-ed and the return value is added to the repr unconditionally:

https://github.com/python-attrs/attrs/blob/c849440ac93d5f33578e9e0d1b1d8f26fbd590ae/src/attr/_make.py#L1874-L1878

hynek avatar Oct 21 '23 08:10 hynek

Unfortunately, what you want it is currently not possible. The repr function only receives the value that's being repr-ed and the return value is added to the repr unconditionally:

https://github.com/python-attrs/attrs/blob/c849440ac93d5f33578e9e0d1b1d8f26fbd590ae/src/attr/_make.py#L1874-L1878

@hynek Is this something you'd be interesting in having added. If so, I can look into the codebase and see if it falls into something I could make a PR for.

RNKuhns avatar Feb 07 '24 15:02 RNKuhns

If someone came up with a good PR, I would merge it.

But I would strongly suggest to discuss your implementation approach with us first, before you put work into this that doesn't have a chance to be merged!

hynek avatar Feb 26 '24 05:02 hynek

@hynek that sounds reasonable to me.

I've been looking at the code in attrs/src/attr/_make.py.

I'm going to do a bit more investigation on where adding the repr fits into the order of things.

I'll make a proposal if something seems workable.

RNKuhns avatar Feb 27 '24 06:02 RNKuhns