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')
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
Asked: 2022-06-26 11:00:00 +0000
Seen: 1 times
Last updated: Mar 17 '22
How can I set up Gunicorn with a Django Project?
Looking for a Python Module that finds Tags for a Text describing its Content
Need a Function in Python to remove entries less than 2 digits from an Array
How can I convert a Document in Python?
How can I program a Loop in Python?
How can I enable Python Code Highlighting in Askbot?