File size: 6,274 Bytes
622387b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
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',