How to use the confuse.util function in confuse

To help you get started, we’ve selected a few confuse examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github beetbox / confuse / confuse / core.py View on Github external
:type obj: argparse.Namespace or optparse.Values or dict or *
        :param dots: If True, any properties on obj that contain dots (.)
            will be broken down into child dictionaries.
        :return: A new dictionary or the value passed if obj was not a
            dict, Namespace, or Values.
        :rtype: dict or *
        """
        # We expect our root object to be a dict, but it may come in as
        # a namespace
        obj = util.namespace_to_dict(obj)
        # We only deal with dictionaries
        if not isinstance(obj, dict):
            return obj

        # Get keys iterator
        keys = obj.keys() if util.PY3 else obj.iterkeys()
        if dots:
            # Dots needs sorted keys to prevent parents from
            # clobbering children
            keys = sorted(list(keys))

        output = {}
        for key in keys:
            value = obj[key]
            if value is None:  # Avoid unset options.
                continue

            save_to = output
            result = cls._build_namespace_dict(value, dots)
            if dots:
                # Split keys by dots as this signifies nesting
                split = key.split('.')
github beetbox / confuse / confuse / core.py View on Github external
def first(self):
        """Return a (value, source) pair for the first object found for
        this view. This amounts to the first element returned by
        `resolve`. If no values are available, a `NotFoundError` is
        raised.
        """
        pairs = self.resolve()
        try:
            return util.iter_first(pairs)
        except ValueError:
            raise NotFoundError(u"{0} not found".format(self.name))
github beetbox / confuse / confuse / templates.py View on Github external
def convert(self, value, view):
        """Check that the value is an int or a float.
        """
        if isinstance(value, util.NUMERIC_TYPES):
            return value
        else:
            self.fail(
                u'must be numeric, not {0}'.format(type(value).__name__),
                view,
                True
            )
github beetbox / confuse / confuse / core.py View on Github external
for a ``config.yaml`` file. If no configuration file is found, a
        fallback path is used.
        """
        # If environment variable is set, use it.
        if self._env_var in os.environ:
            appdir = os.environ[self._env_var]
            appdir = os.path.abspath(os.path.expanduser(appdir))
            if os.path.isfile(appdir):
                raise ConfigError(u'{0} must be a directory'.format(
                    self._env_var
                ))

        else:
            # Search platform-specific locations. If no config file is
            # found, fall back to the first directory in the list.
            configdirs = util.config_dirs()
            for confdir in configdirs:
                appdir = os.path.join(confdir, self.appname)
                if os.path.isfile(os.path.join(appdir, CONFIG_FILENAME)):
                    break
            else:
                appdir = os.path.join(configdirs[0], self.appname)

        # Ensure that the directory exists.
        if not os.path.isdir(appdir):
            os.makedirs(appdir)
        return appdir
github beetbox / confuse / confuse / core.py View on Github external
Additionally, if dots is True, will expand any dot delimited
        keys.

        :param obj: Namespace, Values, or dict to iterate over. Other
            values will simply be returned.
        :type obj: argparse.Namespace or optparse.Values or dict or *
        :param dots: If True, any properties on obj that contain dots (.)
            will be broken down into child dictionaries.
        :return: A new dictionary or the value passed if obj was not a
            dict, Namespace, or Values.
        :rtype: dict or *
        """
        # We expect our root object to be a dict, but it may come in as
        # a namespace
        obj = util.namespace_to_dict(obj)
        # We only deal with dictionaries
        if not isinstance(obj, dict):
            return obj

        # Get keys iterator
        keys = obj.keys() if util.PY3 else obj.iterkeys()
        if dots:
            # Dots needs sorted keys to prevent parents from
            # clobbering children
            keys = sorted(list(keys))

        output = {}
        for key in keys:
            value = obj[key]
            if value is None:  # Avoid unset options.
                continue
github beetbox / confuse / confuse / templates.py View on Github external
def as_template(value):
    """Convert a simple "shorthand" Python value to a `Template`.
    """
    if isinstance(value, Template):
        # If it's already a Template, pass it through.
        return value
    elif isinstance(value, abc.Mapping):
        # Dictionaries work as templates.
        return MappingTemplate(value)
    elif value is int:
        return Integer()
    elif isinstance(value, int):
        return Integer(value)
    elif isinstance(value, type) and issubclass(value, util.BASESTRING):
        return String()
    elif isinstance(value, util.BASESTRING):
        return String(value)
    elif isinstance(value, set):
        # convert to list to avoid hash related problems
        return Choice(list(value))
    elif (SUPPORTS_ENUM and isinstance(value, type)
            and issubclass(value, enum.Enum)):
        return Choice(value)
    elif isinstance(value, list):
        return OneOf(value)
    elif value is float:
        return Number()
    elif isinstance(value, float):
        return Number(value)
    elif value is None:
github beetbox / confuse / confuse / core.py View on Github external
def __unicode__(self):
        """Get the value for this view as a Unicode string.
        """
        return util.STRING(self.get())
github beetbox / confuse / confuse / templates.py View on Github external
def _convert_value(self, x, view):
        try:
            return (super(Pairs, self)._convert_value(x, view),
                    self.default_value)
        except exceptions.ConfigTypeError:
            if isinstance(x, abc.Mapping):
                if len(x) != 1:
                    self.fail(u'must be a single-element mapping', view, True)
                k, v = util.iter_first(x.items())
            elif isinstance(x, abc.Sequence):
                if len(x) != 2:
                    self.fail(u'must be a two-element list', view, True)
                k, v = x
            else:
                # Is this even possible? -> Likely, if some !directive cause
                # YAML to parse this to some custom type.
                self.fail(u'must be a single string, mapping, or a list'
                          u'' + str(x),
                          view, True)
            return (super(Pairs, self)._convert_value(k, view),
                    super(Pairs, self)._convert_value(v, view))
github beetbox / confuse / confuse / templates.py View on Github external
def as_template(value):
    """Convert a simple "shorthand" Python value to a `Template`.
    """
    if isinstance(value, Template):
        # If it's already a Template, pass it through.
        return value
    elif isinstance(value, abc.Mapping):
        # Dictionaries work as templates.
        return MappingTemplate(value)
    elif value is int:
        return Integer()
    elif isinstance(value, int):
        return Integer(value)
    elif isinstance(value, type) and issubclass(value, util.BASESTRING):
        return String()
    elif isinstance(value, util.BASESTRING):
        return String(value)
    elif isinstance(value, set):
        # convert to list to avoid hash related problems
        return Choice(list(value))
    elif (SUPPORTS_ENUM and isinstance(value, type)
            and issubclass(value, enum.Enum)):
        return Choice(value)
    elif isinstance(value, list):
        return OneOf(value)
    elif value is float:
        return Number()
    elif isinstance(value, float):
        return Number(value)
    elif value is None:
        return Template(None)
    elif value is REQUIRED:
github beetbox / confuse / confuse / templates.py View on Github external
def _convert_value(self, x, view):
        if isinstance(x, util.STRING):
            return x
        elif isinstance(x, bytes):
            return x.decode('utf-8', 'ignore')
        else:
            self.fail(u'must be a list of strings', view, True)