# HG changeset patch # User Franz Glasner # Date 1457439118 -3600 # Node ID e4c63b4f1568da4eac249f888b64cb48a4e76a95 # Parent 53ea2bc254e79ef0d3f56b8ffe52d4593358c3cb Provide a yaml wrapper that import with all-unicode strings on Python2 but does not path the Loader globally diff -r 53ea2bc254e7 -r e4c63b4f1568 mixconfig/yaml.py --- /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)