Python yaml.constructor() Examples

The following are 11 code examples of yaml.constructor(). 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: config.py    From visual_dynamics with MIT License 6 votes vote down vote up
def __repr__(self, config=None):
        class_name = self.__class__.__name__
        config = config or self._get_config()
        # attributes (including properties) that are in config
        attr_dict = {k: getattr(self, k) for k in dir(self) if k in config}
        # order attributes based in the order in which they appear in the constructor
        ordered_attr_pairs = []
        for arg_name in get_signature_args(self.__init__):
            try:
                ordered_attr_pairs.append((arg_name, attr_dict.pop(arg_name)))
            except KeyError:
                pass
        # add remaining attributes that doesn't appear in the constructor
        ordered_attr_pairs += list(attr_dict.items())
        kwargs = ', '.join(['%s=%r' % (k, v) for (k, v) in ordered_attr_pairs])
        return "%s(%s)" % (class_name, kwargs) 
Example #3
Source File: yaml_ordered_dict.py    From CityEnergyAnalyst with MIT License 6 votes vote down vote up
def construct_mapping(self, node, deep=False):
        if isinstance(node, yaml.MappingNode):
            self.flatten_mapping(node)
        else:
            raise yaml.constructor.ConstructorError(None, None,
                'expected a mapping node, but found %s' % node.id, node.start_mark)

        mapping = OrderedDict()
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            try:
                hash(key)
            except TypeError as exc:
                raise yaml.constructor.ConstructorError('while constructing a mapping',
                    node.start_mark, 'found unacceptable key (%s)' % exc, key_node.start_mark)
            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value
        return mapping 
Example #4
Source File: curriculum.py    From MADRL with MIT License 6 votes vote down vote up
def construct_mapping(self, node, deep=False):
        if isinstance(node, yaml.MappingNode):
            self.flatten_mapping(node)
        else:
            raise yaml.constructor.ConstructorError(None, None,
                                                    'expected a mapping node, but found %s' %
                                                    node.id, node.start_mark)

        mapping = OrderedDict()
        for key_node, value_node in node.value:
            key = self.construct_object(key_node, deep=deep)
            try:
                hash(key)
            except TypeError as exc:
                raise yaml.constructor.ConstructorError('while constructing a mapping',
                                                        node.start_mark,
                                                        'found unacceptable key (%s)' % exc,
                                                        key_node.start_mark)
            value = self.construct_object(value_node, deep=deep)
            mapping[key] = value
        return mapping 
Example #5
Source File: test_trtable.py    From dipper with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testIfTableIsAMap(self):

        from yaml.constructor import ConstructorError

        try:
            from yaml import CLoader as Loader
        except ImportError:
            from yaml import Loader

        # Credit https://gist.github.com/pypt/94d747fe5180851196eb
        def no_duplicates_constructor(loader, node, deep=False):
            """Check for duplicate keys."""

            mapping = {}
            for key_node, value_node in node.value:
                key = loader.construct_object(key_node, deep=deep)
                value = loader.construct_object(value_node, deep=deep)
                if key in mapping:
                    raise ConstructorError(
                        "while constructing a mapping", node.start_mark,
                        "found duplicate key (%s)" % key, key_node.start_mark)
                mapping[key] = value

            return loader.construct_mapping(node, deep)

        yaml.add_constructor(yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG, no_duplicates_constructor)

        file_path = '../translationtable/GLOBAL_TERMS.yaml'
        if os.path.exists(os.path.join(os.path.dirname(__file__), file_path)):
            tt_file = open(os.path.join(os.path.dirname(__file__), file_path), 'r')
            try:
                translation_table = yaml.safe_load(tt_file)
            except yaml.constructor.ConstructorError as e:
                tt_file.close()
                self.assertTrue(False)
                print(e)
            tt_file.close() 
Example #6
Source File: yaml_parse.py    From TextDetector with GNU General Public License v3.0 5 votes vote down vote up
def construct_mapping(node, deep=False):
    # This is a modified version of yaml.BaseConstructor.construct_mapping
    # in which a repeated key raises a ConstructorError
    if not isinstance(node, yaml.nodes.MappingNode):
        const = yaml.constructor
        message = "expected a mapping node, but found"
        raise const.ConstructorError(None, None,
                                     "%s %s " % (message, node.id),
                                     node.start_mark)
    mapping = {}
    constructor = yaml.constructor.BaseConstructor()
    for key_node, value_node in node.value:
        key = constructor.construct_object(key_node, deep=False)
        try:
            hash(key)
        except TypeError as exc:
            const = yaml.constructor
            reraise_as(const.ConstructorError("while constructing a mapping",
                                              node.start_mark,
                                              "found unacceptable key (%s)" %
                                              (exc, key_node.start_mark)))
        if key in mapping:
            const = yaml.constructor
            raise const.ConstructorError("while constructing a mapping",
                                         node.start_mark,
                                         "found duplicate key (%s)" % key)
        value = constructor.construct_object(value_node, deep=False)
        mapping[key] = value
    return mapping 
Example #7
Source File: loader.py    From tavern with MIT License 5 votes vote down vote up
def constructor(_):
        raise NotImplementedError 
Example #8
Source File: loader.py    From tavern with MIT License 5 votes vote down vote up
def __str__(self):
        return "<Tavern YAML sentinel for {}>".format(self.constructor) 
Example #9
Source File: loader.py    From tavern with MIT License 5 votes vote down vote up
def constructor(_):
        raise NotImplementedError 
Example #10
Source File: loader.py    From tavern with MIT License 5 votes vote down vote up
def from_yaml(cls, loader, node):
        value = loader.construct_scalar(node)

        try:
            # See if it's already a valid value (eg, if we do `!int "2"`)
            converted = cls.constructor(value)
        except ValueError:
            # If not (eg, `!int "{int_value:d}"`)
            return cls(value)
        else:
            return converted 
Example #11
Source File: loader.py    From tavern with MIT License 5 votes vote down vote up
def constructor(_):
        raise ValueError


# Sort-of hack to try and avoid future API changes