Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

python - Avoid references in PyYAML

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.

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))

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.load1:

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

yaml.Dumper.ignore_aliases = lambda *args : True

yaml.dump(x, sys.stdout)

will get you:

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

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.

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.


1 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...