[英]YAML to use repr/str when printing an object
I have a dictionary where keys are objects.我有一本字典,其中键是对象。 These objects can be thought as tuple wrappers and they do implement both
__hash__
and __repr__
.这些对象可以被认为是元组包装器,它们确实实现了
__hash__
和__repr__
。
example = {
Coordinates(0,0): Rome,
Coordinates(0,1): Zurich
}
I want to print the dictionary with yaml
, using the repr of the object.我想使用对象的 repr 用
yaml
打印字典。 This would be the desired output:这将是所需的输出:
(0, 0): Rome
(0, 1): Zurich
Instead, what I get is:相反,我得到的是:
? !!python/object:__main__.Coordinates
x: 0
y: 0
: Rome
? !!python/object:__main__.Coordinates
x: 0
y: 1
: Zurich
I'm doing the transformation via:我正在通过以下方式进行转换:
import yaml
print(yaml.dump(example, allow_unicode=True, default_flow_style=False))
The only solution I found so far is to coerce everything to str()
manually myself.到目前为止,我找到的唯一解决方案是自己手动将所有内容强制转换为
str()
。 Is there a more elegant solution?有没有更优雅的解决方案?
Assuming the type Coordinates
exists, this would be the setup:假设类型
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)
The DEFAULT_SCALAR_TAG
ensures that PyYAML doesn't dump an explicit tag for the scalar (x, y)
. DEFAULT_SCALAR_TAG
确保 PyYAML 不会为标量(x, y)
转储显式标签。 You may want to use an actual YAML sequence instead:您可能希望改用实际的 YAML 序列:
def coord_representer(dumper, data):
return dumper.represent_sequence(BaseResolver.DEFAULT_SEQUENCE_TAG,
[data.x, data.y], flow_style=[True, True])
This will yield [x, y]
, a YAML flow sequence.这将产生
[x, y]
,一个 YAML 流序列。 Problem is that this is tricky to read in again, as PyYAML would by default construct a list from it, which cannot be used as dict key.问题是这很难再次读取,因为 PyYAML 默认情况下会从中构造一个列表,该列表不能用作 dict 键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.