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)
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.
¹ In ruamel.yaml, of which I am the author, which is an enhanced version of PyYAML, capable of handling YAML 1.2, you can do:
yaml = ruamel.yaml.YAML()
yaml.representer.ignore_aliases = lambda *args: True
x = {(1, t):1, (2, tuple(t)):2}
?a=(1,); a is tuple(a)
also predicts that there is no new tuple.tuple(list(t))
works :)