从python`dataClass“ __repr__”中排除默认字段
摘要
我有 dataclass
带有 10+字段。 print()
将它们埋在默认墙壁中的有趣上下文 - 让我们不必要地重复这些内容使它们变得更加友好。
python中的dataclasses
python's ( pep 557 )提供自动可打印表示( <
假设此示例,基于Python 。
from dataclasses import dataclass
@dataclass
class InventoryItem:
name: str
unit_price: float = 1.00
quantity_on_hand: int = 0
- ,ret, - %3A%20if%20true%20(“ rel =“ noreferrer”> @dataclass(repl = true)
(默认)Will print> print()
不错的输出:
InventoryItem(name='Apple', unit_price='1.00', quantity_on_hand=0)
我想要的:跳过打印默认值
包括您不想显示的隐含默认值。
print(InventoryItem("Apple"))
# Outputs: InventoryItem(name='Apple', unit_price='1.00', quantity_on_hand=0)
# I want: InventoryItem(name='Apple')
print(InventoryItem("Apple", unit_price="1.05"))
# Outputs: InventoryItem(name='Apple', unit_price='1.05', quantity_on_hand=0)
# I want: InventoryItem(name='Apple', unit_price='1.05')
print(InventoryItem("Apple", quantity_on_hand=3))
# Outputs: InventoryItem(name='Apple', unit_price=1.00, quantity_on_hand=3)
# I want: InventoryItem(name='Apple', quantity_on_hand=3)
print(InventoryItem("Apple", unit_price='2.10', quantity_on_hand=3))
# Output is fine (everything's custom):
# InventoryItem(name='Apple', unit_price=2.10, quantity_on_hand=3)
reprep
它打印 all
字段, 这是 dataclass的机械
repr
- python 3.10.4
: cls .__ spr.__ epr __
= “ noreferrer”>
> - &gt; _repr_fn(flds,flds,Globals))
)
_recursive_repr(fn)
可能是 @dataclass(repl = false)
被关闭, def> def __repr __(self):
被添加。
如果是这样,那会是什么样?我们不想包括可选默认值。
上下文
在实践中重复我的 dataclass
具有 10+字段。
我是 print()
通过运行代码和替代实例,以及 @pytest.mark.mark.parametrize
运行 pytest 带有 -vvv
。
大数据类别的非默认值(有时是输入)是无法看到的,因为它们被埋在默认字段中,更糟糕的是,每个默认情况下,每个默认情况都不比例地且令人分心的巨大:掩盖其他有价值的东西带来了印刷。
相关问题
截至今天, dataClass
问题还不多(可能会更改):
- 扩展数据级'__repr__编程:这是试图 limand限制 repr。除非明确覆盖,否则应显示少字段。
- python dataclass生成哈希,排除不安全领域:哈希且与默认值无关。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以这样做:
You could do it like this: