36 |
36 |
integer_re = re.compile('-?[0-9]+')
|
37 |
37 |
|
38 |
38 |
|
39 |
|
def unpack(pathstr, sep='.'):
|
40 |
|
"""
|
41 |
|
>>> unpack('a.-2.x')
|
42 |
|
['a', -2, 'x']
|
43 |
|
"""
|
44 |
|
names = pathstr.split(sep)
|
45 |
|
parse = lambda x: int(x) if integer_re.match(x) else x
|
46 |
|
return [parse(x) for x in names]
|
|
39 |
def join_path(sep, path):
|
|
40 |
iterable = ((str(n) if isinstance(n, (int, long)) else n) for n in path)
|
|
41 |
return sep.join(iterable)
|
47 |
42 |
|
48 |
43 |
|
49 |
|
def lookup_path(container, path, createpath=False):
|
|
44 |
def lookup_path(container, path, sep='.', createpath=False):
|
50 |
45 |
"""
|
51 |
46 |
return (['a','b'],
|
52 |
47 |
[container['a'], container['a']['b']],
|
53 |
|
'c') where path=['a','b','c']
|
|
48 |
'c') where path=sep.join(['a','b','c'])
|
54 |
49 |
|
55 |
50 |
"""
|
56 |
|
dirnames = path[:-1]
|
57 |
|
basename = path[-1]
|
|
51 |
names = path.split(sep)
|
|
52 |
dirnames = names[:-1]
|
|
53 |
basename = names[-1]
|
|
54 |
if integer_re.match(basename):
|
|
55 |
basename = int(basename)
|
58 |
56 |
|
59 |
57 |
node = container
|
60 |
58 |
name_path = []
|
61 |
59 |
node_path = [node]
|
62 |
60 |
for name in dirnames:
|
63 |
61 |
name_path.append(name)
|
|
62 |
|
|
63 |
if integer_re.match(name):
|
|
64 |
name = int(name)
|
|
65 |
|
64 |
66 |
try:
|
65 |
67 |
node = node[name]
|
66 |
68 |
except KeyError as e:
|
67 |
69 |
if not createpath:
|
68 |
|
m = "{0}: path not found".format(name_path)
|
|
70 |
m = "'{0}': path not found".format(join_path(sep, name_path))
|
69 |
71 |
raise KeyError(m)
|
70 |
72 |
node[name] = {}
|
71 |
73 |
node = node[name]
|
72 |
74 |
except IndexError as e:
|
73 |
75 |
if not createpath:
|
74 |
|
m = "{0}: path not found: {1}".format(name_path, e)
|
|
76 |
m = "'{0}': path not found: {1}".format(
|
|
77 |
join_path(sep, name_path), e)
|
75 |
78 |
raise KeyError(m)
|
76 |
79 |
size = name if name > 0 else -name
|
77 |
80 |
node += (dict() for _ in xrange(len(node), size))
|
78 |
81 |
node = node[name]
|
79 |
82 |
except TypeError as e:
|
80 |
|
m = "{0}: cannot traverse path beyond this node: {1}"
|
81 |
|
m = m.format(name_path, str(e))
|
|
83 |
m = "'{0}': cannot traverse path beyond this node: {1}"
|
|
84 |
m = m.format(join_path(sep, name_path), str(e))
|
82 |
85 |
raise ValueError(m)
|
83 |
86 |
node_path.append(node)
|
84 |
87 |
|
... | ... | |
94 |
97 |
yield [name] + names, [node] + nodes
|
95 |
98 |
|
96 |
99 |
|
97 |
|
def list_paths(container):
|
|
100 |
def list_paths(container, sep='.'):
|
98 |
101 |
"""
|
99 |
102 |
>>> sorted(list_paths({'a': {'b': {'c': 'd'}}}))
|
100 |
|
[(['a', 'b', 'c'], 'd')]
|
|
103 |
[('a.b.c', 'd')]
|
101 |
104 |
>>> sorted(list_paths({'a': {'b': {'c': 'd'}, 'e': 3}}))
|
102 |
|
[(['a', 'b', 'c'], 'd'), (['a', 'e'], 3)]
|
|
105 |
[('a.b.c', 'd'), ('a.e', 3)]
|
103 |
106 |
>>> sorted(list_paths({'a': {'b': {'c': 'd'}, 'e': {'f': 3}}}))
|
104 |
|
[(['a', 'b', 'c'], 'd'), (['a', 'e', 'f'], 3)]
|
|
107 |
[('a.b.c', 'd'), ('a.e.f', 3)]
|
105 |
108 |
>>> sorted(list_paths({'a': [{'b': 3}, 2]}))
|
106 |
|
[(['a'], [{'b': 3}, 2])]
|
|
109 |
[('a', [{'b': 3}, 2])]
|
107 |
110 |
>>> list_paths({})
|
108 |
111 |
[]
|
109 |
112 |
|
110 |
113 |
"""
|
111 |
|
return [(name_path, node_path[-1])
|
|
114 |
return [(join_path(sep, name_path), node_path[-1])
|
112 |
115 |
for name_path, node_path in walk_paths(container)]
|
113 |
116 |
|
114 |
117 |
|
115 |
|
def del_path(container, path, collect=True):
|
|
118 |
def del_path(container, path, sep='.', collect=True):
|
116 |
119 |
"""
|
117 |
|
del container['a']['b']['c'] where path=['a','b','c']
|
|
120 |
del container['a']['b']['c'] where path=sep.join(['a','b','c'])
|
118 |
121 |
|
119 |
|
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, ['a', 'b', 'c']); d
|
|
122 |
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, 'a.b.c'); d
|
120 |
123 |
{}
|
121 |
|
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, ['a', 'b', 'c'],\
|
122 |
|
collect=False); d
|
|
124 |
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, 'a.b.c', collect=False); d
|
123 |
125 |
{'a': {'b': {}}}
|
124 |
|
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, ['a', 'b', 'c', 'd'])
|
|
126 |
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, 'a.b.c.d')
|
125 |
127 |
Traceback (most recent call last):
|
126 |
|
ValueError: ['a', 'b', 'c']: cannot traverse path beyond this node:\
|
|
128 |
ValueError: 'a.b.c': cannot traverse path beyond this node:\
|
127 |
129 |
'str' object does not support item deletion
|
128 |
130 |
"""
|
129 |
131 |
|
130 |
132 |
name_path, node_path, basename = \
|
131 |
|
lookup_path(container, path, createpath=False)
|
|
133 |
lookup_path(container, path, sep=sep, createpath=False)
|
132 |
134 |
|
133 |
135 |
lastnode = node_path.pop()
|
|
136 |
lastname = basename
|
134 |
137 |
try:
|
135 |
138 |
if basename in lastnode:
|
136 |
139 |
del lastnode[basename]
|
137 |
140 |
except (TypeError, KeyError) as e:
|
138 |
|
m = "{0}: cannot traverse path beyond this node: {1}"
|
139 |
|
m = m.format(name_path, str(e))
|
|
141 |
m = "'{0}': cannot traverse path beyond this node: {1}"
|
|
142 |
m = m.format(join_path(sep, name_path), str(e))
|
140 |
143 |
raise ValueError(m)
|
141 |
144 |
|
142 |
145 |
if collect:
|
... | ... | |
146 |
149 |
del lastnode[basename]
|
147 |
150 |
|
148 |
151 |
|
149 |
|
def get_path(container, path):
|
|
152 |
def get_path(container, path, sep='.'):
|
150 |
153 |
"""
|
151 |
|
return container['a']['b']['c'] where path=['a','b','c']
|
|
154 |
return container['a']['b']['c'] where path=sep.join(['a','b','c'])
|
152 |
155 |
|
153 |
|
>>> get_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'c', 'd'])
|
|
156 |
>>> get_path({'a': {'b': {'c': 'd'}}}, 'a.b.c.d')
|
154 |
157 |
Traceback (most recent call last):
|
155 |
|
ValueError: ['a', 'b', 'c', 'd']: cannot traverse path beyond this node:\
|
|
158 |
ValueError: 'a.b.c.d': cannot traverse path beyond this node:\
|
156 |
159 |
string indices must be integers, not str
|
157 |
|
>>> get_path({'a': {'b': {'c': 1}}}, ['a', 'b', 'c', 'd'])
|
|
160 |
>>> get_path({'a': {'b': {'c': 1}}}, 'a.b.c.d')
|
158 |
161 |
Traceback (most recent call last):
|
159 |
|
ValueError: ['a', 'b', 'c', 'd']: cannot traverse path beyond this node:\
|
160 |
|
'int' object has no attribute '__getitem__'
|
161 |
|
>>> get_path({'a': {'b': {'c': 1}}}, ['a', 'b', 'c'])
|
|
162 |
ValueError: 'a.b.c.d': cannot traverse path beyond this node:\
|
|
163 |
'int' object is unsubscriptable
|
|
164 |
>>> get_path({'a': {'b': {'c': 1}}}, 'a.b.c')
|
162 |
165 |
1
|
163 |
|
>>> get_path({'a': {'b': {'c': 1}}}, ['a', 'b'])
|
|
166 |
>>> get_path({'a': {'b': {'c': 1}}}, 'a.b')
|
164 |
167 |
{'c': 1}
|
165 |
|
>>> get_path({'a': [{'z': 1}]}, ['a', 'b'])
|
166 |
|
Traceback (most recent call last):
|
167 |
|
ValueError: ['a', 'b']: cannot traverse path beyond this node:\
|
168 |
|
list indices must be integers, not str
|
169 |
|
>>> get_path({'a': [{'z': 1}]}, ['a', 0])
|
|
168 |
>>> get_path({'a': [{'z': 1}]}, 'a.0')
|
170 |
169 |
{'z': 1}
|
171 |
|
>>> get_path({'a': [{'z': 1}]}, ['a', 1])
|
172 |
|
Traceback (most recent call last):
|
173 |
|
KeyError: "['a', 1]: path not found: list index out of range"
|
174 |
|
>>> get_path({'a': [{'z': 1}]}, ['a', 0, 'z'])
|
|
170 |
>>> get_path({'a': [{'z': 1}]}, 'a.0.z')
|
175 |
171 |
1
|
176 |
|
>>> get_path({'a': [{'z': 1}]}, ['a', -1, 'z'])
|
|
172 |
>>> get_path({'a': [{'z': 1}]}, 'a.-1.z')
|
177 |
173 |
1
|
178 |
174 |
|
179 |
175 |
"""
|
180 |
176 |
name_path, node_path, basename = \
|
181 |
|
lookup_path(container, path, createpath=False)
|
|
177 |
lookup_path(container, path, sep=sep, createpath=False)
|
182 |
178 |
name_path.append(basename)
|
183 |
179 |
node = node_path[-1]
|
184 |
180 |
|
185 |
181 |
try:
|
186 |
182 |
return node[basename]
|
187 |
183 |
except TypeError as e:
|
188 |
|
m = "{0}: cannot traverse path beyond this node: {1}"
|
189 |
|
m = m.format(name_path, str(e))
|
|
184 |
m = "'{0}': cannot traverse path beyond this node: {1}"
|
|
185 |
m = m.format(join_path(sep, name_path), str(e))
|
190 |
186 |
raise ValueError(m)
|
191 |
187 |
except KeyError as e:
|
192 |
|
m = "{0}: path not found: {1}"
|
193 |
|
m = m.format(name_path, str(e))
|
194 |
|
raise KeyError(m)
|
195 |
|
except IndexError as e:
|
196 |
|
m = "{0}: path not found: {1}"
|
197 |
|
m = m.format(name_path, str(e))
|
|
188 |
m = "'{0}': path not found: {1}"
|
|
189 |
m = m.format(join_path(sep, name_path), str(e))
|
198 |
190 |
raise KeyError(m)
|
199 |
191 |
|
200 |
192 |
|
201 |
|
def set_path(container, path, value, createpath=False, overwrite=True):
|
|
193 |
def set_path(container, path, value, sep='.',
|
|
194 |
createpath=False, overwrite=True):
|
202 |
195 |
"""
|
203 |
|
container['a']['b']['c'] = value where path=['a','b','c']
|
|
196 |
container['a']['b']['c'] = value where path=sep.join(['a','b','c'])
|
204 |
197 |
|
205 |
|
>>> set_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'c', 'd'], 1)
|
|
198 |
>>> set_path({'a': {'b': {'c': 'd'}}}, 'a.b.c.d', 1)
|
206 |
199 |
Traceback (most recent call last):
|
207 |
|
ValueError: ['a', 'b', 'c', 'd']: cannot index, node is neither dict nor\
|
208 |
|
list
|
209 |
|
>>> set_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'x', 'd'], 1)
|
|
200 |
ValueError: 'a.b.c.d': cannot index non-object node with string
|
|
201 |
>>> set_path({'a': {'b': {'c': 'd'}}}, 'a.b.x.d', 1)
|
210 |
202 |
Traceback (most recent call last):
|
211 |
|
KeyError: "['a', 'b', 'x']: path not found"
|
212 |
|
>>> set_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'x', 'd'], 1,\
|
213 |
|
createpath=True)
|
214 |
|
|
215 |
|
>>> set_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'c'], 1)
|
216 |
|
|
217 |
|
>>> set_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'c'], 1, overwrite=False)
|
|
203 |
KeyError: "'a.b.x': path not found"
|
|
204 |
>>> set_path({'a': {'b': {'c': 'd'}}}, 'a.b.x.d', 1, createpath=True)
|
|
205 |
|
|
206 |
>>> set_path({'a': {'b': {'c': 'd'}}}, 'a.b.c', 1)
|
|
207 |
|
|
208 |
>>> set_path({'a': {'b': {'c': 'd'}}}, 'a.b.c', 1, overwrite=False)
|
218 |
209 |
Traceback (most recent call last):
|
219 |
|
ValueError: will not overwrite path ['a', 'b', 'c']
|
220 |
|
>>> d = {'a': [{'z': 1}]}; set_path(d, ['a', -2, 1], 2, createpath=False)
|
|
210 |
ValueError: will not overwrite path 'a.b.c'
|
|
211 |
>>> d = {'a': [{'z': 1}]}; set_path(d, 'a.-2.1', 2, createpath=False)
|
221 |
212 |
Traceback (most recent call last):
|
222 |
|
KeyError: "['a', -2]: path not found: list index out of range"
|
223 |
|
>>> d = {'a': [{'z': 1}]}; set_path(d, ['a', -2, 1], 2, createpath=True); \
|
224 |
|
d['a'][-2][1]
|
|
213 |
KeyError: "'a.-2': path not found: list index out of range"
|
|
214 |
>>> d = {'a': [{'z': 1}]}; set_path(d, 'a.-2.1', 2, createpath=True)
|
|
215 |
Traceback (most recent call last):
|
|
216 |
ValueError: 'a.-2.1': will not index object node with integer
|
|
217 |
>>> d = {'a': [{'z': 1}]}; set_path(d, 'a.-2.z', 2, createpath=True); \
|
|
218 |
d['a'][-2]['z']
|
225 |
219 |
2
|
226 |
220 |
|
227 |
221 |
"""
|
228 |
222 |
name_path, node_path, basename = \
|
229 |
|
lookup_path(container, path, createpath=createpath)
|
|
223 |
lookup_path(container, path, sep=sep, createpath=createpath)
|
230 |
224 |
name_path.append(basename)
|
231 |
225 |
node = node_path[-1]
|
232 |
226 |
|
233 |
227 |
if basename in node and not overwrite:
|
234 |
|
m = "will not overwrite path {0}".format(path)
|
|
228 |
m = "will not overwrite path '{0}'".format(path)
|
235 |
229 |
raise ValueError(m)
|
236 |
230 |
|
237 |
231 |
is_object_node = hasattr(node, 'keys')
|
238 |
|
is_list_node = isinstance(node, list)
|
239 |
|
if not is_object_node and not is_list_node:
|
240 |
|
m = "{0}: cannot index, node is neither dict nor list"
|
241 |
|
m = m.format(name_path)
|
|
232 |
is_string_name = isinstance(basename, basestring)
|
|
233 |
if not is_string_name and is_object_node:
|
|
234 |
m = "'{0}': will not index object node with integer"
|
|
235 |
m = m.format(join_path(sep, name_path))
|
242 |
236 |
raise ValueError(m)
|
243 |
|
|
244 |
|
is_integer = isinstance(basename, (int, long))
|
245 |
|
if is_list_node and not is_integer:
|
246 |
|
m = "{0}: cannot index list node without an integer"
|
247 |
|
m = m.format(name_path)
|
|
237 |
if is_string_name and not is_object_node:
|
|
238 |
m = "'{0}': cannot index non-object node with string"
|
|
239 |
m = m.format(join_path(sep, name_path))
|
248 |
240 |
raise ValueError(m)
|
249 |
241 |
try:
|
250 |
242 |
node[basename] = value
|
251 |
243 |
except TypeError as e:
|
252 |
|
m = "{0}: cannot traverse path beyond this node: {1}"
|
253 |
|
m = m.format(name_path, str(e))
|
|
244 |
m = "'{0}': cannot traverse path beyond this node: {1}"
|
|
245 |
m = m.format(join_path(sep, name_path), str(e))
|
254 |
246 |
raise ValueError(m)
|
255 |
247 |
|
256 |
248 |
|