Python yaml.add_implicit_resolver() Examples

The following are 4 code examples of yaml.add_implicit_resolver(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module yaml , or try the search function .
Example #1
Source File: yaml_parse.py    From TextDetector with GNU General Public License v3.0 7 votes vote down vote up
def initialize():
    """
    Initialize the configuration system by installing YAML handlers.
    Automatically done on first call to load() specified in this file.
    """
    global is_initialized

    # Add the custom multi-constructor
    yaml.add_multi_constructor('!obj:', multi_constructor_obj)
    yaml.add_multi_constructor('!pkl:', multi_constructor_pkl)
    yaml.add_multi_constructor('!import:', multi_constructor_import)

    yaml.add_constructor('!import', constructor_import)
    yaml.add_constructor("!float", constructor_float)

    pattern = re.compile(SCIENTIFIC_NOTATION_REGEXP)
    yaml.add_implicit_resolver('!float', pattern)

    is_initialized = True


###############################################################################
# Callbacks used by PyYAML 
Example #2
Source File: loader.py    From agents-aea with Apache License 2.0 6 votes vote down vote up
def _config_loader():
    envvar_matcher = re.compile(r"\${([^}^{]+)\}")

    def envvar_constructor(_loader, node):  # pragma: no cover
        """Extract the matched value, expand env variable, and replace the match."""
        node_value = node.value
        match = envvar_matcher.match(node_value)
        env_var = match.group()[2:-1]

        # check for defaults
        var_name, default_value = env_var.split(":")
        var_name = var_name.strip()
        default_value = default_value.strip()
        var_value = os.getenv(var_name, default_value)
        return var_value + node_value[match.end() :]

    yaml.add_implicit_resolver("!envvar", envvar_matcher, None, SafeLoader)
    yaml.add_constructor("!envvar", envvar_constructor, SafeLoader)


# TODO: instead of this, create custom loader and use it
#       by wrapping yaml.safe_load to use it 
Example #3
Source File: config.py    From prometheus-pgbouncer-exporter with MIT License 5 votes vote down vote up
def read(self, filepath):
        stream = False

        # Setup environment variables replacement
        def env_var_single_replace(match):
            return os.environ[match.group(1)] if match.group(1) in os.environ else match.group()

        def env_var_multi_replacer(loader, node):
            value = loader.construct_scalar(node)

            return re.sub(ENV_VAR_REPLACER_PATTERN, env_var_single_replace, value)

        yaml.add_implicit_resolver("!envvarreplacer", ENV_VAR_MATCHER_PATTERN)
        yaml.add_constructor('!envvarreplacer', env_var_multi_replacer)

        # Read file
        try:
            stream = open(filepath, "r")
            self.config = yaml.load(stream)

            # Handle an empty configuration file
            if not self.config:
                self.config = {}
        finally:
            if stream:
                stream.close() 
Example #4
Source File: parsing.py    From bellybutton with MIT License 5 votes vote down vote up
def constructor(tag=None, pattern=None):
    """Register custom constructor with pyyaml."""
    def decorator(f):
        if tag is None or f is tag:
            tag_ = '!{}'.format(f.__name__)
        else:
            tag_ = tag
        yaml.add_constructor(tag_, f)
        if pattern is not None:
            yaml.add_implicit_resolver(tag_, re.compile(pattern))
        return f
    if callable(tag):  # little convenience hack to avoid empty arg list
        return decorator(tag)
    return decorator