changeset 1:e4c63b4f1568

Provide a yaml wrapper that import with all-unicode strings on Python2 but does not path the Loader globally
author Franz Glasner <f.glasner@feldmann-mg.com>
date Tue, 08 Mar 2016 13:11:58 +0100
parents 53ea2bc254e7
children 9981a68040b6
files mixconfig/yaml.py
diffstat 1 files changed, 60 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/mixconfig/yaml.py	Tue Mar 08 13:11:58 2016 +0100
@@ -0,0 +1,60 @@
+# -*- coding: utf-8 -*-
+r"""Simple wrapper for yaml to support all-unicode strings when loading
+configuration files.
+
+"""
+
+from __future__ import division, print_function, absolute_import
+
+import yaml
+
+
+__all__ = ["safe_load", "safe_load_all", "load", "load_all"]
+
+
+class ConfigLoader(yaml.Loader):
+
+    """A YAML loader, which makes all !!str strings to Unicode.  Standard
+    PyYAML does this only in the non-ASCII case.
+
+    """
+
+    def construct_yaml_str(self, node):
+        return self.construct_scalar(node)
+
+
+ConfigLoader.add_constructor(
+    "tag:yaml.org,2002:str",
+    ConfigLoader.construct_yaml_str)
+
+
+class ConfigSafeLoader(yaml.SafeLoader):
+
+    """A safe YAML loader, which makes all !!str strings to Unicode.
+    Standard PyYAML does this only in the non-ASCII case.
+
+    """
+
+    def construct_yaml_str(self, node):
+        return self.construct_scalar(node)
+
+
+ConfigSafeLoader.add_constructor(
+    "tag:yaml.org,2002:str",
+    ConfigSafeLoader.construct_yaml_str)
+
+
+def load(stream, Loader=ConfigLoader):
+    return yaml.load(stream, Loader)
+
+
+def load_all(stream, Loader=ConfigLoader):
+    return yaml.load_all(stream, Loader)
+
+
+def safe_load(stream):
+    return yaml.load(stream, Loader=ConfigSafeLoader)
+
+
+def safe_load_all(stream):
+    return yaml.load_all(stream, Loader=ConfigSafeLoader)