views:

182

answers:

3

I have

>>> import yaml
>>> yaml.dump(u'abc')
"!!python/unicode 'abc'\n"

But I want

>>> import yaml
>>> yaml.dump(u'abc', magic='something')
'abc\n'

What magic param forces no tagging?

A: 

This worked for me, but I'd much rather something official (and which won't break with ' in the input)

output = yaml.dump(input, default_flow_style=False).replace("!!python/unicode ", "").replace("'", '')
Paul Tarjan
+2  A: 

You can use safe_dump instead of dump. Just keep in mind that it won't be able to represent arbitrary Python objects then. Also, when you load the YAML, you will get a str object instead of unicode.

interjay
safe_dump seems to force a '...' at the end, but that's easy to fix
Paul Tarjan
+1  A: 

How about this:

def unicode_representer(dumper, uni):
    node = yaml.ScalarNode(tag=u'tag:yaml.org,2002:str', value=uni)
    return node

yaml.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'
Michał Marczyk