Mercurial > hgrepos > Python > libs > ConfigMix
comparison mixconfig/yaml.py @ 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 | |
| children | bedc4f95b9e9 |
comparison
equal
deleted
inserted
replaced
| 0:53ea2bc254e7 | 1:e4c63b4f1568 |
|---|---|
| 1 # -*- coding: utf-8 -*- | |
| 2 r"""Simple wrapper for yaml to support all-unicode strings when loading | |
| 3 configuration files. | |
| 4 | |
| 5 """ | |
| 6 | |
| 7 from __future__ import division, print_function, absolute_import | |
| 8 | |
| 9 import yaml | |
| 10 | |
| 11 | |
| 12 __all__ = ["safe_load", "safe_load_all", "load", "load_all"] | |
| 13 | |
| 14 | |
| 15 class ConfigLoader(yaml.Loader): | |
| 16 | |
| 17 """A YAML loader, which makes all !!str strings to Unicode. Standard | |
| 18 PyYAML does this only in the non-ASCII case. | |
| 19 | |
| 20 """ | |
| 21 | |
| 22 def construct_yaml_str(self, node): | |
| 23 return self.construct_scalar(node) | |
| 24 | |
| 25 | |
| 26 ConfigLoader.add_constructor( | |
| 27 "tag:yaml.org,2002:str", | |
| 28 ConfigLoader.construct_yaml_str) | |
| 29 | |
| 30 | |
| 31 class ConfigSafeLoader(yaml.SafeLoader): | |
| 32 | |
| 33 """A safe YAML loader, which makes all !!str strings to Unicode. | |
| 34 Standard PyYAML does this only in the non-ASCII case. | |
| 35 | |
| 36 """ | |
| 37 | |
| 38 def construct_yaml_str(self, node): | |
| 39 return self.construct_scalar(node) | |
| 40 | |
| 41 | |
| 42 ConfigSafeLoader.add_constructor( | |
| 43 "tag:yaml.org,2002:str", | |
| 44 ConfigSafeLoader.construct_yaml_str) | |
| 45 | |
| 46 | |
| 47 def load(stream, Loader=ConfigLoader): | |
| 48 return yaml.load(stream, Loader) | |
| 49 | |
| 50 | |
| 51 def load_all(stream, Loader=ConfigLoader): | |
| 52 return yaml.load_all(stream, Loader) | |
| 53 | |
| 54 | |
| 55 def safe_load(stream): | |
| 56 return yaml.load(stream, Loader=ConfigSafeLoader) | |
| 57 | |
| 58 | |
| 59 def safe_load_all(stream): | |
| 60 return yaml.load_all(stream, Loader=ConfigSafeLoader) |
