Search code examples
python-attrs

Only show non-default attributes in repr of attr.s class


I'm using attrs to define simple classes without boilerplate code. The decorator automatically generates a __repr__ that shows the values for all attributes. I'd like to only show attributes that do not have their default values:

>>> import attr
>>> @attr.s
... class Coordinates(object):
...     x = attr.ib(default=0)
...     y = attr.ib(default=0)
>>> Coordinates()  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=0, y=0)  # wanted output: Coordinates()
Coordinates(x=0, y=0)
>>> Coordinates(x=1)  # wanted output: Coordinates(x=1)
Coordinates(x=1, y=0)
>>> Coordinates(x=1, y=1)  # output OK
Coordinates(x=1, y=1)

Is there any reasonably easy way to achieve this?


Solution

  • No, there’s not and it’s also a fairly specific request. :) People have been asking for more ways to customise repr’s output by passing e.g. callable so that might make your use case easier, once it lands. However I’m not aware of anyone actively working on that right now.