Benjamin-eecs's picture
release v1: 65 held-out tasks, 78 bootstrap records, r2e_local adapter, manifest ae94c40b (part 4)
622387b verified
Raw History Blame Contribute Delete
6.27 kB
diff --git a/confuse.py b/confuse.py
index a9c2f96..0460499 100644
--- a/confuse.py
+++ b/confuse.py
@@ -17,6 +17,8 @@
"""
from __future__ import division, absolute_import, print_function
+import argparse
+import optparse
import platform
import os
import pkgutil
@@ -60,6 +62,21 @@ def iter_first(sequence):
raise ValueError()
+def namespace_to_dict(obj):
+ """If obj is argparse.Namespace or optparse.Values we'll return
+ a dict representation of it, else return the original object.
+
+ Redefine this method if using other parsers.
+
+ :param obj: *
+ :return:
+ :rtype: dict or *
+ """
+ if isinstance(obj, (argparse.Namespace, optparse.Values)):
+ return vars(obj)
+ return obj
+
+
# Exceptions.
class ConfigError(Exception):
@@ -243,15 +260,86 @@ class ConfigView(object):
def __contains__(self, key):
return self[key].exists()
- def set_args(self, namespace):
+ @classmethod
+ def _build_namespace_dict(cls, obj, dots=False):
+ """Recursively replaces all argparse.Namespace and optparse.Values
+ with dicts and drops any keys with None values.
+
+ 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 = namespace_to_dict(obj)
+ # We only deal with dictionaries
+ if not isinstance(obj, dict):
+ return obj
+
+ # Get keys iterator
+ keys = obj.keys() if 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('.')
+ if len(split) > 1:
+ # The last index will be the key we assign result to
+ key = split.pop()
+ # Build the dict tree if needed and change where
+ # we're saving to
+ for child_key in split:
+ if child_key in save_to and \
+ isinstance(save_to[child_key], dict):
+ save_to = save_to[child_key]
+ else:
+ # Clobber or create
+ save_to[child_key] = {}
+ save_to = save_to[child_key]
+
+ # Save
+ if key in save_to:
+ save_to[key].update(result)
+ else:
+ save_to[key] = result
+ return output
+
+ def set_args(self, namespace, dots=False):
"""Overlay parsed command-line arguments, generated by a library
like argparse or optparse, onto this view's value.
+
+ :param namespace: Dictionary or Namespace to overlay this config with.
+ Supports nested Dictionaries and Namespaces.
+ :type namespace: dict or Namespace
+ :param dots: If True, any properties on namespace that contain dots (.)
+ will be broken down into child dictionaries.
+ :Example:
+
+ {'foo.bar': 'car'}
+ # Will be turned into
+ {'foo': {'bar': 'car'}}
+ :type dots: bool
"""
- args = {}
- for key, value in namespace.__dict__.items():
- if value is not None: # Avoid unset options.
- args[key] = value
- self.set(args)
+ self.set(self._build_namespace_dict(namespace, dots))
# Magical conversions. These special methods make it possible to use
# View objects somewhat transparently in certain circumstances. For
diff --git a/docs/index.rst b/docs/index.rst
index c900a37..a3c7e14 100644
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -167,6 +167,24 @@ consider this argparse script::
This will allow the user to override the configured value for key
``foo`` by passing ``--foo <something>`` on the command line.
+Overriding nested values can be accomplished by passing `dots=True` and
+have dot-delimited properties on the incoming object.::
+
+ parser.add_argument('--bar', help='nested parameter', dest='foo.bar')
+ args = parser.parse_args() # args looks like: {'foo.bar': 'value'}
+ config.set_args(args, dots=True)
+ print(config['foo']['bar'].get())
+
+`parse_args` works with generic dictionaries too.::
+
+ args = {
+ 'foo': {
+ 'bar': 1
+ }
+ }
+ config.set_args(args, dots=True)
+ print(config['foo']['bar'].get())
+
.. _argparse: http://docs.python.org/dev/library/argparse.html
.. _parse_args: http://docs.python.org/library/argparse.html#the-parse-args-method
.. _optparse: http://docs.python.org/library/optparse.html
diff --git a/example/__init__.py b/example/__init__.py
index 0717181..33b4306 100644
--- a/example/__init__.py
+++ b/example/__init__.py
@@ -23,7 +23,7 @@ def main():
parser = argparse.ArgumentParser(description='example Confuse program')
parser.add_argument('--library', '-l', dest='library', metavar='LIBPATH',
help='library database file')
- parser.add_argument('--directory', '-d', dest='directory',
+ parser.add_argument('--directory', '-d', dest='paths.directory',
metavar='DIRECTORY',
help='destination music directory')
parser.add_argument('--verbose', '-v', dest='verbose', action='store_true',