Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enhancement: exclude default from reprs of some dataclass types #3379

Open
peterschutt opened this issue Apr 12, 2024 · 1 comment
Open

Enhancement: exclude default from reprs of some dataclass types #3379

peterschutt opened this issue Apr 12, 2024 · 1 comment
Labels
Enhancement This is a new feature or request

Comments

@peterschutt
Copy link
Contributor

peterschutt commented Apr 12, 2024

Summary

We have some dataclasses with a lot of fields, and the reprs can be a bit overwhelming, especially when included in logs/warnings/exceptions.

Request is for reprs to exclude fields where their value is == the field default.

KwargDefinition (and subtypes) and the OpenAPI spec models are examples of types that would benefit from this.

Basic Example

ParameterKwarg(examples=None, external_docs=None, content_encoding=None, default=<_EmptyEnum.EMPTY: 0>, title=None, description=None, const=None, gt=None, ge=3, lt=None, le=None, multiple_of=None, min_items=None, max_items=None, min_length=None, max_length=None, pattern=None, lower_case=None, upper_case=None, format=None, enum=None, read_only=None, schema_extra=None, annotation=<_EmptyEnum.EMPTY: 0>, header=None, cookie=None, query=None, required=None)

vs

ParameterKwarg(ge=3)

Drawbacks and Impact

Pros: easier to parse and reason about.
Cons: maybe some users prefer the verbosity.

Unresolved questions

Could changing the reprs of these things be considered breaking??


Note

While we are open for sponsoring on GitHub Sponsors and
OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.
Fund with Polar
@peterschutt peterschutt added the Enhancement This is a new feature or request label Apr 12, 2024
@peterschutt
Copy link
Contributor Author

Possible implementation:

    def __repr__(self) -> str:
        """Exclude fields with values equal to the field default."""
        kv_pairs = (f"{f.name}={getattr(self, f.name)!r}" for f in fields(self) if getattr(self, f.name) != f.default)
        return f"{self.__class__.__name__}({', '.join(kv_pairs)})"

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Enhancement This is a new feature or request
Projects
Status: Triage
Development

No branches or pull requests

1 participant