![](/img/trans.png)
[英]How can printing an object result in different output than both str() and repr()?
[英]YAML to use repr/str when printing an object
我有一本字典,其中键是对象。 这些对象可以被认为是元组包装器,它们确实实现了__hash__
和__repr__
。
example = {
Coordinates(0,0): Rome,
Coordinates(0,1): Zurich
}
我想使用对象的 repr 用yaml
打印字典。 这将是所需的输出:
(0, 0): Rome
(0, 1): Zurich
相反,我得到的是:
? !!python/object:__main__.Coordinates
x: 0
y: 0
: Rome
? !!python/object:__main__.Coordinates
x: 0
y: 1
: Zurich
我正在通过以下方式进行转换:
import yaml
print(yaml.dump(example, allow_unicode=True, default_flow_style=False))
到目前为止,我找到的唯一解决方案是自己手动将所有内容强制转换为str()
。 有没有更优雅的解决方案?
假设类型Coordinates
存在,这将是设置:
import yaml
from yaml.resolver import BaseResolver
def coord_representer(dumper, data):
return dumper.represent_scalar(BaseResolver.DEFAULT_SCALAR_TAG,
data.__repr__())
yaml.add_representer(Coordinates, coord_representer)
DEFAULT_SCALAR_TAG
确保 PyYAML 不会为标量(x, y)
转储显式标签。 您可能希望改用实际的 YAML 序列:
def coord_representer(dumper, data):
return dumper.represent_sequence(BaseResolver.DEFAULT_SEQUENCE_TAG,
[data.x, data.y], flow_style=[True, True])
这将产生[x, y]
,一个 YAML 流序列。 问题是这很难再次读取,因为 PyYAML 默认情况下会从中构造一个列表,该列表不能用作 dict 键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.