Ask Your Question
4

How can we display only the non-default attributes in the repr method of an attr.s class?

asked 2022-06-26 11:00:00 +0000

qstack gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-17 12:00:00 +0000

scrum gravatar image

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') 
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-06-26 11:00:00 +0000

Seen: 13 times

Last updated: Mar 17 '22