From 26078aca895c49f3c5e910f6df9c634eb0283409 Mon Sep 17 00:00:00 2001 From: Monty Taylor Date: Fri, 30 Sep 2016 11:06:36 -0700 Subject: [PATCH] Emit long strings using yaml multiline syntax It's nicer to read. --- flamel/__init__.py | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/flamel/__init__.py b/flamel/__init__.py index 8d8791a..cc1a85c 100755 --- a/flamel/__init__.py +++ b/flamel/__init__.py @@ -22,6 +22,28 @@ import os +# from: +# http://stackoverflow.com/questions/8640959/how-can-i-control-what-scalar-form-pyyaml-uses-for-my-data flake8: noqa +def should_use_block(value): + for c in u"\u000a\u000d\u001c\u001d\u001e\u0085\u2028\u2029": + if c in value: + return True + return False + +def my_represent_scalar(self, tag, value, style=None): + if style is None: + if should_use_block(value): + style='|' + else: + style = self.default_style + + node = yaml.representer.ScalarNode(tag, value, style=style) + if self.alias_key is not None: + self.represented_objects[self.alias_key] = node + return node + +yaml.representer.BaseRepresenter.represent_scalar = my_represent_scalar + class YamlOrderedLoader(yaml.SafeLoader): """Specialized Loader which respects order.""" @@ -48,7 +70,7 @@ def unicode_representer(dumper, uni): OrderedDumper.add_representer(collections.OrderedDict, _dict_representer) OrderedDumper.add_representer(collections.defaultdict, _dict_representer) OrderedDumper.add_representer(unicode, unicode_representer) - return yaml.dump(data, stream, OrderedDumper, **kwds) + return yaml.safe_dump(data, stream, OrderedDumper, **kwds) def yaml_load(data):