1 | initial version |
To display only non-default attributes in the repr method of an attr.s class, we can make use of the attr.asdict
function to convert the instance into a dictionary and then filter out the attributes with default values.
Here's an example:
import attr @attr.s class MyClass: x: int = attr.ib(default=0) y: str = attr.ib(default='foo') z: str = attr.ib() # no default value def __repr__(self): filtered_attrs = {k: v for k, v in attr.asdict(self, filter=lambda attr, value: not attr.default)(inherited=False).items()} return f"MyClass({', '.join(f'{k}={v!r}' for k, v in filtered_attrs.items())})"
In this example, we use the filter
parameter of the attr.asdict()
function to exclude attributes that have default values. The inherited=False
parameter ensures that only the attributes directly defined in the class are included.
Now, if we create an instance of MyClass
, only non-default attributes will be displayed in the repr()
method:
>>> m = MyClass(z='bar') >>> m MyClass(z='bar')