避免在 PyYAML 中引用 [英] Avoid references in PyYAML

查看:38
本文介绍了避免在 PyYAML 中引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 YAML 与 PyYAML 一起使用.有没有办法在转储嵌套结构后避免 *id002 引用?为了便于阅读,我想在那里看到实际的(元组)值.

I use YAML with PyYAML. Is there a way to avoid the *id002 references after dumping a nested structure? For readability I'd like to see the actual (tuple) values there.

在尝试制作一个小例子时,我注意到它只在我使用相同的 id 对象时发生:

While trying to produce a mini example I noticed that it only happens when I use the same id object:

import yaml

t = ("b", "c")
x = {(1, t):1, (2, t):2, }
print(yaml.dump(x))

所以我认为 copy.copy() 会解决这个问题,但是对于元组它似乎不起作用:( 我可以创建一个具有不同 id 的新元组吗?

So I thought copy.copy() would solve the problem, however for tuples it doesn't seem to work :( Can I create a new tuple with a different id?

推荐答案

PyYAML dumper 使用 ignore_aliases 方法来防止原始类型以这种方式锚定"和引用".您可以覆盖该方法以始终忽略传入的任何对象的别名.默认情况下,yaml.Loader 类用于 yaml.load¹:

The PyYAML dumper uses an ignore_aliases method to prevent primitive types from being "anchored" and "referenced" in this way. You can override that method to always ignore_aliases independent of any object passed in. And by default the yaml.Loader class is used in yaml.load¹:

t = ("b", "c")
x = {(1, t):1, (2, t):2, }

yaml.Dumper.ignore_aliases = lambda *args : True

yaml.dump(x, sys.stdout)

会得到你:

? !!python/tuple
- 1
- !!python/tuple [b, c]
: 1
? !!python/tuple
- 2
- !!python/tuple [b, c]
: 2

这样你就不必尽最大努力让具有相同散列的元组看起来不同.您可能希望将 yaml.load 上的 default_flow_style 参数提供给 FalseTrue 以获得不同的布局输出.

That way you don't have to try your best and get tuples with the same hash to look different. You might want to provide the default_flow_style parameter on yaml.load to False or True to get different layouts of the output.

您无法使其工作的原因是表示器匹配 id() 的结果,并且只要元素相同,对于单独生成的两个元组来说,结果也是相同的.

The reason you could not get this to work is that the representer matches the result of id() and that is the same for two tuples generated separately as long as the elements are the same.

¹ 我只用 ruamel.yaml 尝试了这个,其中我我是作者,它是 PyYAML 的增强版本,但为此两者的工作方式应该相同.

¹ I only tried this with ruamel.yaml, of which I am the author, it is an enhanced version of PyYAML, but for this both should work the same.

这篇关于避免在 PyYAML 中引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆