Add hide_defaults argument to dataclass that excludes default fields from repr

Add a hide_defaults argument to dataclass that excludes fields having default values from the repr.

This would unclutter the repr of dataclasses with many fields. See this question for context as well as an example implementation.

I assume you’d want to use == to test equality. But what about things like 1==1.0?

You mean whether to check type(a) == type(b)?

Presumably you’re going to have code that says “if the value of self.x is not equal to the default value of x, then show self.x in the repr”. I’m trying to understand that equality test.

A simple == equality test seems fine to me. So 1 would be considered equal to 1.0.

What about the option to define a custom representation, with False hiding the attribute?

class A:
   a : float = field(repr=lambda x: False if x==1 else f'{x:.4f})

This would leave the choice of which equality method to use to the user

Something like that could work, but False is a valid thing to show. You’d probably want

class _NoShow:

NoShow = _NoShow()

then have it so if repr returns (or i guess equals) NoShow, it just wouldn’t show in repr:

from dataclasses import dataclass, NoShow
class A:
   a : float = field(repr=NoShow)

# or

class A:
   a : float = field(repr=lambda x: NoShow if x == 0 else x)

I would probably say to not shadow repr itself but come up with a different name.

The other question is: should it be modifying __repr__ or should it be modifying a __str__ method?

@eendebakpt @csm10495 If I understand correctly, these seem orthogonal to the proposal, which is a single flag set for the dataclass as a whole.

You are right. Both proposals allow to hide fields front the repr. Your proposal is a single flag on the dataclass, the other proposal is per field.

Perhaps these additions to dataclasses are better suited for external packages such as attrs. In the pep introducing dataclasses PEP 557 – Data Classes | it is written:

Data Classes makes a tradeoff to achieve simplicity by not implementing these features.

(this is in general, not in particular about the feature from this thread)

Most options for data-classes are also options for their fields as well: think of the field inheriting the default value specified for the class.

In any case, I agree that attrs is the better place for this.