forked from faif/python-patterns
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomposite.py
More file actions
Latest commit
326 lines (244 loc) · 9.36 KB
/
Copy pathcomposite.py
File metadata and controls
326 lines (244 loc) · 9.36 KB
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
"""
A class which defines a composite object which can store
hieararchical dictionaries with names.
This class is same as a hiearchical dictionary, but it
provides methods to add/access/modify children by name,
like a Composite.
Created Anand B Pillai <abpillai@gmail.com>
"""
__author__="Anand B Pillai"
__maintainer__="Anand B Pillai"
__version__="0.2"
defnormalize(val):
""" Normalize a string so that it can be used as an attribute
to a Python object """
ifval.find('-') !=-1:
val=val.replace('-','_')
returnval
defdenormalize(val):
""" De-normalize a string """
ifval.find('_') !=-1:
val=val.replace('_','-')
returnval
classSpecialDict(dict):
""" A dictionary type which allows direct attribute
access to its keys """
def__getattr__(self, name):
ifnameinself.__dict__:
returnself.__dict__[name]
elifnameinself:
returnself.get(name)
else:
# Check for denormalized name
name=denormalize(name)
ifnameinself:
returnself.get(name)
else:
raiseAttributeError('no attribute named %s'%name)
def__setattr__(self, name, value):
ifnameinself.__dict__:
self.__dict__[name] =value
elifnameinself:
self[name] =value
else:
# Check for denormalized name
name2=denormalize(name)
ifname2inself:
self[name2] =value
else:
# New attribute
self[name] =value
classCompositeDict(SpecialDict):
""" A class which works like a hierarchical dictionary.
This class is based on the Composite design-pattern """
ID=0
def__init__(self, name=''):
ifname:
self._name=name
else:
self._name=''.join(('id#',str(self.__class__.ID)))
self.__class__.ID+=1
self._children= []
# Link back to father
self._father=None
self[self._name] =SpecialDict()
def__getattr__(self, name):
ifnameinself.__dict__:
returnself.__dict__[name]
elifnameinself:
returnself.get(name)
else:
# Check for denormalized name
name=denormalize(name)
ifnameinself:
returnself.get(name)
else:
# Look in children list
child=self.findChild(name)
ifchild:
returnchild
else:
attr=getattr(self[self._name], name)
ifattr: returnattr
raiseAttributeError('no attribute named %s'%name)
defisRoot(self):
""" Return whether I am a root component or not """
# If I don't have a parent, I am root
returnnotself._father
defisLeaf(self):
""" Return whether I am a leaf component or not """
# I am a leaf if I have no children
returnnotself._children
defgetName(self):
""" Return the name of this ConfigInfo object """
returnself._name
defgetIndex(self, child):
""" Return the index of the child ConfigInfo object 'child' """
ifchildinself._children:
returnself._children.index(child)
else:
return-1
defgetDict(self):
""" Return the contained dictionary """
returnself[self._name]
defgetProperty(self, child, key):
""" Return the value for the property for child
'child' with key 'key' """
# First get the child's dictionary
childDict=self.getInfoDict(child)
ifchildDict:
returnchildDict.get(key, None)
defsetProperty(self, child, key, value):
""" Set the value for the property 'key' for
the child 'child' to 'value' """
# First get the child's dictionary
childDict=self.getInfoDict(child)
ifchildDict:
childDict[key] =value
defgetChildren(self):
""" Return the list of immediate children of this object """
returnself._children
defgetAllChildren(self):
""" Return the list of all children of this object """
l= []
forchildinself._children:
l.append(child)
l.extend(child.getAllChildren())
returnl
defgetChild(self, name):
""" Return the immediate child object with the given name """
forchildinself._children:
ifchild.getName() ==name:
returnchild
deffindChild(self, name):
""" Return the child with the given name from the tree """
# Note - this returns the first child of the given name
# any other children with similar names down the tree
# is not considered.
forchildinself.getAllChildren():
ifchild.getName() ==name:
returnchild
deffindChildren(self, name):
""" Return a list of children with the given name from the tree """
# Note: this returns a list of all the children of a given
# name, irrespective of the depth of look-up.
children= []
forchildinself.getAllChildren():
ifchild.getName() ==name:
children.append(child)
returnchildren
defgetPropertyDict(self):
""" Return the property dictionary """
d=self.getChild('__properties')
ifd:
returnd.getDict()
else:
return {}
defgetParent(self):
""" Return the person who created me """
returnself._father
def__setChildDict(self, child):
""" Private method to set the dictionary of the child
object 'child' in the internal dictionary """
d=self[self._name]
d[child.getName()] =child.getDict()
defsetParent(self, father):
""" Set the parent object of myself """
# This should be ideally called only once
# by the father when creating the child :-)
# though it is possible to change parenthood
# when a new child is adopted in the place
# of an existing one - in that case the existing
# child is orphaned - see addChild and addChild2
# methods !
self._father=father
defsetName(self, name):
""" Set the name of this ConfigInfo object to 'name' """
self._name=name
defsetDict(self, d):
""" Set the contained dictionary """
self[self._name] =d.copy()
defsetAttribute(self, name, value):
""" Set a name value pair in the contained dictionary """
self[self._name][name] =value
defgetAttribute(self, name):
""" Return value of an attribute from the contained dictionary """
returnself[self._name][name]
defaddChild(self, name, force=False):
""" Add a new child 'child' with the name 'name'.
If the optional flag 'force' is set to True, the
child object is overwritten if it is already there.
This function returns the child object, whether
new or existing """
iftype(name) !=str:
raiseValueError('Argument should be a string!')
child=self.getChild(name)
ifchild:
# print 'Child %s present!' % name
# Replace it if force==True
ifforce:
index=self.getIndex(child)
ifindex!=-1:
child=self.__class__(name)
self._children[index] =child
child.setParent(self)
self.__setChildDict(child)
returnchild
else:
child=self.__class__(name)
child.setParent(self)
self._children.append(child)
self.__setChildDict(child)
returnchild
defaddChild2(self, child):
""" Add the child object 'child'. If it is already present,
it is overwritten by default """
currChild=self.getChild(child.getName())
ifcurrChild:
index=self.getIndex(currChild)
ifindex!=-1:
self._children[index] =child
child.setParent(self)
# Unset the existing child's parent
currChild.setParent(None)
delcurrChild
self.__setChildDict(child)
else:
child.setParent(self)
self._children.append(child)
self.__setChildDict(child)
if__name__=="__main__":
window=CompositeDict('Window')
frame=window.addChild('Frame')
tfield=frame.addChild('Text Field')
tfield.setAttribute('size','20')
btn=frame.addChild('Button1')
btn.setAttribute('label','Submit')
btn=frame.addChild('Button2')
btn.setAttribute('label','Browse')
# print(window)
# print(window.Frame)
# print(window.Frame.Button1)
# print(window.Frame.Button2)
print(window.Frame.Button1.label)
print(window.Frame.Button2.label)