pyyaml: dumping without tags
How about this:
def unicode_representer(dumper, uni): node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni) return nodeyaml.add_representer(unicode, unicode_representer)
This seems to make dumping unicode objects work the same as dumping str objects for me (Python 2.6).
In [72]: yaml.dump(u'abc')Out[72]: 'abc\n...\n'In [73]: yaml.dump('abc')Out[73]: 'abc\n...\n'In [75]: yaml.dump(['abc'])Out[75]: '[abc]\n'In [76]: yaml.dump([u'abc'])Out[76]: '[abc]\n'
You need a new dumper class that does everything the standard Dumper class does but overrides the representers for str and unicode.
from yaml.dumper import Dumperfrom yaml.representer import SafeRepresenterclass KludgeDumper(Dumper): passKludgeDumper.add_representer(str, SafeRepresenter.represent_str)KludgeDumper.add_representer(unicode, SafeRepresenter.represent_unicode)
Which leads to
>>> print yaml.dump([u'abc',u'abc\xe7'],Dumper=KludgeDumper)[abc, "abc\xE7"]>>> print yaml.dump([u'abc',u'abc\xe7'],Dumper=KludgeDumper,encoding=None)[abc, "abc\xE7"]
Granted, I'm still stumped on how to keep this pretty.
>>> print u'abc\xe7'abcç
And it breaks a later yaml.load()
>>> yy=yaml.load(yaml.dump(['abc','abc\xe7'],Dumper=KludgeDumper,encoding=None))>>> yy['abc', 'abc\xe7']>>> print yy[1]abc�>>> print u'abc\xe7'abcç