This repository has been archived by the owner on Mar 11, 2018. It is now read-only.
/
dataStructures.py
332 lines (263 loc) · 9.16 KB
/
dataStructures.py
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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
**dataStructures.py**
**Platform:**
Windows, Linux, Mac Os X.
**Description:**
This module defines **Foundations** package data structures objects.
**Others:**
"""
#**********************************************************************************************************************
#*** External imports.
#**********************************************************************************************************************
import logging
import sys
if sys.version_info[:2] == (2, 6):
from ordereddict import OrderedDict
else:
from collections import OrderedDict
#**********************************************************************************************************************
#*** Internal imports.
#**********************************************************************************************************************
import foundations.core as core
from foundations.globals.constants import Constants
#**********************************************************************************************************************
#*** Module attributes.
#**********************************************************************************************************************
__author__ = "Thomas Mansencal"
__copyright__ = "Copyright (C) 2008 - 2012 - Thomas Mansencal"
__license__ = "GPL V3.0 - http://www.gnu.org/licenses/"
__maintainer__ = "Thomas Mansencal"
__email__ = "thomas.mansencal@gmail.com"
__status__ = "Production"
__all__ = ["LOGGER",
"NestedAttribute",
"Structure",
"OrderedStructure",
"Lookup"]
LOGGER = logging.getLogger(Constants.logger)
#**********************************************************************************************************************
#*** Module classes and definitions.
#**********************************************************************************************************************
class NestedAttribute(object):
"""
This class is an helper object providing methods to manipulate nested attributes.
Usage:
>>> nest = NestedAttribute()
>>> nest.my.nested.attribute = "Value"
>>> nest.my.nested.attribute
Value
>>> nest.another.very.deeply.nested.attribute = 64
>>> nest.another.very.deeply.nested.attribute
64
"""
# @core.executionTrace
def __getattr__(self, attribute):
"""
This method returns requested attribute.
:param attribute: Attribute name. ( String )
:return: Attribute. ( Object )
"""
self.__dict__[attribute] = NestedAttribute()
return self.__dict__[attribute]
# @core.executionTrace
def __setattr__(self, attribute, value):
"""
This method sets given attribute with given value.
:param attribute: Attribute name. ( String )
:param name: Attribute value. ( Object )
"""
namespaces = attribute.split(".")
object.__setattr__(reduce(object.__getattribute__, namespaces[:-1], self), namespaces[-1], value)
# @core.executionTrace
def __delattr__(self, attribute):
"""
This method deletes given attribute with.
:param attribute: Attribute name. ( String )
"""
namespaces = attribute.split(".")
object.__delattr__(reduce(object.__getattribute__, namespaces[:-1], self), namespaces[-1])
class Structure(dict):
"""
This class creates an object similar to C/C++ structured type.
Usage:
>>> person = Structure(firstName="Doe", lastName="John", gender="male")
>>> person.firstName
'Doe'
>>> person.keys()
['gender', 'firstName', 'lastName']
>>> person["gender"]
'male'
>>> del(person["gender"])
>>> person["gender"]
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'gender'
>>> person.gender
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Structure' object has no attribute 'gender'
"""
@core.executionTrace
def __init__(self, *args, **kwargs):
"""
This method initializes the class.
:param \*args: Arguments. ( \* )
:param \*\*kwargs: Key / Value pairs. ( Key / Value pairs )
"""
dict.__init__(self, **kwargs)
self.__dict__.update(**kwargs)
# @core.executionTrace
def __getattr__(self, attribute):
"""
This method returns given attribute value.
:return: Attribute value. ( Object )
"""
try:
return dict.__getitem__(self, attribute)
except KeyError:
raise AttributeError("'{0}' object has no attribute '{1}'".format(self.__class__.__name__, attribute))
# @core.executionTrace
def __setattr__(self, attribute, value):
"""
This method sets both key and sibling attribute with given value.
:param attribute.: Attribute. ( Object )
:param value.: Value. ( Object )
"""
dict.__setitem__(self, attribute, value)
object.__setattr__(self, attribute, value)
__setitem__ = __setattr__
# @core.executionTrace
def __delattr__(self, attribute):
"""
This method deletes both key and sibling attribute.
:param attribute.: Attribute. ( Object )
"""
dict.__delitem__(self, attribute)
object.__delattr__(self, attribute)
__delitem__ = __delattr__
# @core.executionTrace
def update(self, *args, **kwargs):
"""
This method reimplements the :meth:`Dict.update` method.
:param \*args: Arguments. ( \* )
:param \*\*kwargs: Keywords arguments. ( \*\* )
"""
dict.update(self, *args, **kwargs)
self.__dict__.update(*args, **kwargs)
class OrderedStructure(OrderedDict):
"""
| This class creates an object similar to C/C++ structured type.
| Contrary to the :class:`Structure` since this class inherits from :class:`collections.OrderedDict`,
its content is ordered.
Usage:
>>> people = OrderedStructure([("personA", "John"), ("personB", "Jane"), ("personC", "Luke")])
>>> people
OrderedStructure([('personA', 'John'), ('personB', 'Jane'), ('personC', 'Luke')])
>>> people.keys()
['personA', 'personB', 'personC']
>>> people.personA
'John'
>>> del(people["personA"])
>>> people["personA"]
Traceback (most recent call last):
File "<console>", line 1, in <module>
KeyError: 'personA'
>>> people.personA
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'OrderedStructure' object has no attribute 'personA'
>>> people.personB = "Kate"
>>> people["personB"]
'Kate'
>>> people.personB
'Kate'
"""
@core.executionTrace
def __init__(self, *args, **kwargs):
"""
This method initializes the class.
:param \*args: Arguments. ( \* )
:param \*\*kwargs: Key / Value pairs. ( Key / Value pairs )
"""
OrderedDict.__init__(self, *args, **kwargs)
# @core.executionTrace
def __setitem__(self, key, value, *args, **kwargs):
"""
This method sets a key and sibling attribute with given value.
:param key.: Key. ( Object )
:param value.: Value. ( Object )
:param \*args: Arguments. ( \* )
:param \*\*kwargs: Key / Value pairs. ( Key / Value pairs )
"""
OrderedDict.__setitem__(self, key, value, *args, **kwargs)
OrderedDict.__setattr__(self, key, value)
# @core.executionTrace
def __delitem__(self, key, *args, **kwargs):
"""
This method deletes both key and sibling attribute.
:param key.: Key. ( Object )
:param \*args: Arguments. ( \* )
:param \*\*kwargs: Key / Value pairs. ( Key / Value pairs )
"""
OrderedDict.__delitem__(self, key, *args, **kwargs)
OrderedDict.__delattr__(self, key)
# @core.executionTrace
def __setattr__(self, attribute, value):
"""
This method sets both key and sibling attribute with given value.
:param attribute.: Attribute. ( Object )
:param value.: Value. ( Object )
"""
if sys.version_info[:2] == (2, 6):
if not attribute in ("_OrderedDict__map", "_OrderedDict__end"):
OrderedDict.__setitem__(self, attribute, value)
else:
if hasattr(self, "_OrderedDict__root") and hasattr(self, "_OrderedDict__map"):
if self._OrderedDict__root:
OrderedDict.__setitem__(self, attribute, value)
OrderedDict.__setattr__(self, attribute, value)
# @core.executionTrace
def __delattr__(self, attribute):
"""
This method deletes both key and sibling attribute.
:param attribute.: Attribute. ( Object )
"""
if sys.version_info[:2] == (2, 6):
if not attribute in ("_OrderedDict__map", "_OrderedDict__end"):
OrderedDict.__delitem__(self, attribute)
else:
if hasattr(self, "_OrderedDict__root") and hasattr(self, "_OrderedDict__map"):
if self._OrderedDict__root:
OrderedDict.__delitem__(self, attribute)
OrderedDict.__delattr__(self, attribute)
class Lookup(dict):
"""
This class extend dict type to provide a lookup by value(s).
Usage:
>>> person = Lookup(firstName="Doe", lastName="John", gender="male")
>>> person.getFirstKeyFromValue("Doe")
'firstName'
>>> persons = foundations.foundations.dataStructures.Lookup(John="Doe", Jane="Doe", Luke="Skywalker")
>>> persons.getKeysFromValue("Doe")
['Jane', 'John']
"""
# @core.executionTrace
def getFirstKeyFromValue(self, value):
"""
This method gets the first key from given value.
:param value.: Value. ( Object )
:return: Key. ( Object )
"""
for key, data in self.iteritems():
if data == value:
return key
# @core.executionTrace
def getKeysFromValue(self, value):
"""
This method gets the keys from given value.
:param value.: Value. ( Object )
:return: Keys. ( Object )
"""
return [key for key, data in self.iteritems() if data == value]