litestar-org / litestar

Production-ready, Light, Flexible and Extensible ASGI API framework | Effortlessly Build Performant APIs
https://litestar.dev/
MIT License
5.34k stars 361 forks source link

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

Open peterschutt opened 4 months ago

peterschutt commented 4 months ago

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 commented 4 months ago

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)})"