如何为省略默认值的“dataclass”定义“__str__”?
给定一个 dataclass 实例,我希望 print() 或 str() 仅列出非默认字段值。当dataclass
有很多字段并且只有少数字段发生变化时,这非常有用。
@dataclasses.dataclass
class X:
a: int = 1
b: bool = False
c: float = 2.0
x = X(b=True)
print(x) # Desired output: X(b=True)
Given a dataclass
instance, I would like print()
or str()
to only list the non-default field values. This is useful when the dataclass
has many fields and only a few are changed.
@dataclasses.dataclass
class X:
a: int = 1
b: bool = False
c: float = 2.0
x = X(b=True)
print(x) # Desired output: X(b=True)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
解决方案是添加自定义
__str__()
函数:这也可以使用装饰器来实现:
The solution is to add a custom
__str__()
function:This can also be achieved using a decorator:
我建议的一项改进是计算
dataclasses.fields
的结果,然后缓存结果中的默认值。这将有助于提高性能,因为当前dataclasses
每次调用时都会评估fields
。这是一个使用元类方法的简单示例。
请注意,我还对其进行了稍微修改,以便它可以处理定义
default_factory
的可变类型字段。最后,这是一个快速而肮脏的测试,以确认缓存实际上有利于重复调用
str()
或print
:结果:
One improvement I would suggest is to compute the result from
dataclasses.fields
and then cache the default values from the result. This will help performance because currentlydataclasses
evaluates thefields
each time it is invoked.Here's a simple example using a metaclass approach.
Note that I've also modified it slightly so it handles mutable-type fields that define a
default_factory
for instance.Finally, here's a quick and dirty test to confirm that caching is actually beneficial for repeated calls to
str()
orprint
:Results: