root / snf-common / synnefo / util / keypath.py @ b10f66b9
History | View | Annotate | Download (8.6 kB)
1 |
# Copyright 2013 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
|
35 |
import re |
36 |
integer_re = re.compile('-?[0-9]+')
|
37 |
|
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] |
47 |
|
48 |
|
49 |
def lookup_path(container, path, createpath=False): |
50 |
"""
|
51 |
return (['a','b'],
|
52 |
[container['a'], container['a']['b']],
|
53 |
'c') where path=['a','b','c']
|
54 |
|
55 |
"""
|
56 |
dirnames = path[:-1]
|
57 |
basename = path[-1]
|
58 |
|
59 |
node = container |
60 |
name_path = [] |
61 |
node_path = [node] |
62 |
for name in dirnames: |
63 |
name_path.append(name) |
64 |
try:
|
65 |
node = node[name] |
66 |
except KeyError as e: |
67 |
if not createpath: |
68 |
m = "{0}: path not found".format(name_path)
|
69 |
raise KeyError(m) |
70 |
node[name] = {} |
71 |
node = node[name] |
72 |
except IndexError as e: |
73 |
if not createpath: |
74 |
m = "{0}: path not found: {1}".format(name_path, e)
|
75 |
raise KeyError(m) |
76 |
size = name if name > 0 else -name |
77 |
node += (dict() for _ in xrange(len(node), size)) |
78 |
node = node[name] |
79 |
except TypeError as e: |
80 |
m = "{0}: cannot traverse path beyond this node: {1}"
|
81 |
m = m.format(name_path, str(e))
|
82 |
raise ValueError(m) |
83 |
node_path.append(node) |
84 |
|
85 |
return name_path, node_path, basename
|
86 |
|
87 |
|
88 |
def walk_paths(container): |
89 |
for name, node in container.iteritems(): |
90 |
if not hasattr(node, 'items'): |
91 |
yield [name], [node]
|
92 |
else:
|
93 |
for names, nodes in walk_paths(node): |
94 |
yield [name] + names, [node] + nodes
|
95 |
|
96 |
|
97 |
def list_paths(container): |
98 |
"""
|
99 |
>>> sorted(list_paths({'a': {'b': {'c': 'd'}}}))
|
100 |
[(['a', 'b', 'c'], 'd')]
|
101 |
>>> sorted(list_paths({'a': {'b': {'c': 'd'}, 'e': 3}}))
|
102 |
[(['a', 'b', 'c'], 'd'), (['a', 'e'], 3)]
|
103 |
>>> sorted(list_paths({'a': {'b': {'c': 'd'}, 'e': {'f': 3}}}))
|
104 |
[(['a', 'b', 'c'], 'd'), (['a', 'e', 'f'], 3)]
|
105 |
>>> sorted(list_paths({'a': [{'b': 3}, 2]}))
|
106 |
[(['a'], [{'b': 3}, 2])]
|
107 |
>>> list_paths({})
|
108 |
[]
|
109 |
|
110 |
"""
|
111 |
return [(name_path, node_path[-1]) |
112 |
for name_path, node_path in walk_paths(container)] |
113 |
|
114 |
|
115 |
def del_path(container, path, collect=True): |
116 |
"""
|
117 |
del container['a']['b']['c'] where path=['a','b','c']
|
118 |
|
119 |
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, ['a', 'b', 'c']); d
|
120 |
{}
|
121 |
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, ['a', 'b', 'c'],\
|
122 |
collect=False); d
|
123 |
{'a': {'b': {}}}
|
124 |
>>> d = {'a': {'b': {'c': 'd'}}}; del_path(d, ['a', 'b', 'c', 'd'])
|
125 |
Traceback (most recent call last):
|
126 |
ValueError: ['a', 'b', 'c']: cannot traverse path beyond this node:\
|
127 |
'str' object does not support item deletion
|
128 |
"""
|
129 |
|
130 |
name_path, node_path, basename = \ |
131 |
lookup_path(container, path, createpath=False)
|
132 |
|
133 |
lastnode = node_path.pop() |
134 |
try:
|
135 |
if basename in lastnode: |
136 |
del lastnode[basename]
|
137 |
except (TypeError, KeyError) as e: |
138 |
m = "{0}: cannot traverse path beyond this node: {1}"
|
139 |
m = m.format(name_path, str(e))
|
140 |
raise ValueError(m) |
141 |
|
142 |
if collect:
|
143 |
while node_path and not lastnode: |
144 |
basename = name_path.pop() |
145 |
lastnode = node_path.pop() |
146 |
del lastnode[basename]
|
147 |
|
148 |
|
149 |
def get_path(container, path): |
150 |
"""
|
151 |
return container['a']['b']['c'] where path=['a','b','c']
|
152 |
|
153 |
>>> get_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'c', 'd'])
|
154 |
Traceback (most recent call last):
|
155 |
ValueError: ['a', 'b', 'c', 'd']: cannot traverse path beyond this node:\
|
156 |
string indices must be integers, not str
|
157 |
>>> get_path({'a': {'b': {'c': 1}}}, ['a', 'b', 'c', 'd'])
|
158 |
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 |
1
|
163 |
>>> get_path({'a': {'b': {'c': 1}}}, ['a', 'b'])
|
164 |
{'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])
|
170 |
{'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'])
|
175 |
1
|
176 |
>>> get_path({'a': [{'z': 1}]}, ['a', -1, 'z'])
|
177 |
1
|
178 |
|
179 |
"""
|
180 |
name_path, node_path, basename = \ |
181 |
lookup_path(container, path, createpath=False)
|
182 |
name_path.append(basename) |
183 |
node = node_path[-1]
|
184 |
|
185 |
try:
|
186 |
return node[basename]
|
187 |
except TypeError as e: |
188 |
m = "{0}: cannot traverse path beyond this node: {1}"
|
189 |
m = m.format(name_path, str(e))
|
190 |
raise ValueError(m) |
191 |
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))
|
198 |
raise KeyError(m) |
199 |
|
200 |
|
201 |
def set_path(container, path, value, createpath=False, overwrite=True): |
202 |
"""
|
203 |
container['a']['b']['c'] = value where path=['a','b','c']
|
204 |
|
205 |
>>> set_path({'a': {'b': {'c': 'd'}}}, ['a', 'b', 'c', 'd'], 1)
|
206 |
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)
|
210 |
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)
|
218 |
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)
|
221 |
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]
|
225 |
2
|
226 |
|
227 |
"""
|
228 |
name_path, node_path, basename = \ |
229 |
lookup_path(container, path, createpath=createpath) |
230 |
name_path.append(basename) |
231 |
node = node_path[-1]
|
232 |
|
233 |
if basename in node and not overwrite: |
234 |
m = "will not overwrite path {0}".format(path)
|
235 |
raise ValueError(m) |
236 |
|
237 |
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) |
242 |
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) |
248 |
raise ValueError(m) |
249 |
try:
|
250 |
node[basename] = value |
251 |
except TypeError as e: |
252 |
m = "{0}: cannot traverse path beyond this node: {1}"
|
253 |
m = m.format(name_path, str(e))
|
254 |
raise ValueError(m) |
255 |
|
256 |
|
257 |
if __name__ == '__main__': |
258 |
import doctest |
259 |
doctest.testmod() |