Welcome, guest | Sign In | My Account | Store | Cart

The recipe illustrates the composite design pattern by using hierarchical dictionaries. It can be used to process hierarchical, tree-based data structures using Python dictionaries.

Python, 326 lines
  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
"""
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"


def normalize(val):
    """ Normalize a string so that it can be used as an attribute
    to a Python object """
    
    if val.find('-') != -1:
        val = val.replace('-','_')

    return val

def denormalize(val):
    """ De-normalize a string """
    
    if val.find('_') != -1:
        val = val.replace('_','-')

    return val

class SpecialDict(dict):
    """ A dictionary type which allows direct attribute
    access to its keys """

    def __getattr__(self, name):

        if name in self.__dict__:
            return self.__dict__[name]
        elif name in self:
            return self.get(name)
        else:
            # Check for denormalized name
            name = denormalize(name)
            if name in self:
                return self.get(name)
            else:
                raise AttributeError,'no attribute named %s' % name

    def __setattr__(self, name, value):

        if name in self.__dict__:
            self.__dict__[name] = value
        elif name in self:
            self[name] = value
        else:
            # Check for denormalized name
            name2 = denormalize(name)
            if name2 in self:
                self[name2] = value
            else:
                # New attribute
                self[name] = value
        
class CompositeDict(SpecialDict):
    """ A class which works like a hierarchical dictionary.
    This class is based on the Composite design-pattern """
    
    ID = 0
    
    def __init__(self, name=''):

        if name:
            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):

        if name in self.__dict__:
            return self.__dict__[name]
        elif name in self:
            return self.get(name)
        else:
            # Check for denormalized name
            name = denormalize(name)
            if name in self:
                return self.get(name)
            else:
                # Look in children list
                child = self.findChild(name)
                if child:
                    return child
                else:
                    attr = getattr(self[self._name], name)
                    if attr: return attr
                    
                    raise AttributeError,'no attribute named %s' % name

    def isRoot(self):
        """ Return whether I am a root component or not """

        # If I don't have a parent, I am root
        return not self._father
    
    def isLeaf(self):
        """ Return whether I am a leaf component or not """

        # I am a leaf if I have no children
        return not self._children

    def getName(self):
        """ Return the name of this ConfigInfo object """

        return self._name

    def getIndex(self, child):
        """ Return the index of the child ConfigInfo object 'child' """
        
        if child in self._children:
            return self._children.index(child)
        else:
            return -1

    def getDict(self):
        """ Return the contained dictionary """
        
        return self[self._name]

    def getProperty(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)
        if childDict:
            return childDict.get(key, None)

    def setProperty(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)
        if childDict:
            childDict[key] = value
    
    def getChildren(self):
        """ Return the list of immediate children of this object """
        
        return self._children

    def getAllChildren(self):
        """ Return the list of all children of this object """
        
        l = []
        for child in self._children:
            l.append(child)
            l.extend(child.getAllChildren())
            
        return l

    def getChild(self, name):
        """ Return the immediate child object with the given name """
        
        for child in self._children:
            if child.getName() == name:
                return child

    def findChild(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.
        
        for child in self.getAllChildren():
            if child.getName() == name:
                return child

    def findChildren(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 = []
        
        for child in self.getAllChildren():
            if child.getName() == name:
                children.append(child)

        return children
            
    def getPropertyDict(self):
        """ Return the property dictionary """
        
        d = self.getChild('__properties')
        if d:
            return d.getDict()
        else:
            return {}
        
    def getParent(self):
        """ Return the person who created me """

        return self._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()

    def setParent(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
        
    def setName(self, name):
        """ Set the name of this ConfigInfo object to 'name' """        

        self._name = name

    def setDict(self, d):
        """ Set the contained dictionary """
        
        self[self._name] = d.copy()
        
    def setAttribute(self, name, value):
        """ Set a name value pair in the contained dictionary """
        
        self[self._name][name] = value

    def getAttribute(self, name):
        """ Return value of an attribute from the contained dictionary """
        
        return self[self._name][name]

    def addChild(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 """
        
        if type(name) != str:
            raise ValueError, 'Argument should be a string!'
        
        child = self.getChild(name)
        if child:
            # print 'Child %s present!' % name
            # Replace it if force==True
            if force:
                index = self.getIndex(child)
                if index != -1:
                    child = self.__class__(name)
                    self._children[index] = child
                    child.setParent(self)
                    
                    self.__setChildDict(child)
            return child
        else:
            child = self.__class__(name)
            child.setParent(self)
            
            self._children.append(child)
            self.__setChildDict(child)

            return child
        
    def addChild2(self, child):
        """ Add the child object 'child'. If it is already present,
        it is overwritten by default """
        
        currChild = self.getChild(child.getName())
        if currChild:
            index = self.getIndex(currChild)
            if index != -1:
                self._children[index] = child
                child.setParent(self)
                # Unset the existing child's parent
                currChild.setParent(None)
                del currChild
                
                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 
    
    

I have seen this recipe to be very useful whenever I have to process hierarchical tree-structures by using Python dictionaries. The CompositeDict class provides powerful processing for such objects on top of the capabilities already provided by the dict type. I have used this class for processing XML files, the Windows registry and for storing GUI widget structures. When combined with pickle, it can be used as a tool to serialize such structures effectively.

1 comment

Cesare Delle Fratte 14 years, 7 months ago  # | flag

I found it very useful, complete and simple to use.

When using it with python multiprocessing manager, sharing the class into a manger and trying to use addChild() method into a process cause a "RuntimeError: maximum recursion depth exceeded" maybe due to the fact that __getattr__, defined into the class SpecialDict, hasn't a proxy so addChild() doesn't get the expected returning value. Of course this problem doesn't come from the pattern implementation.

Created by Anand on Tue, 7 Nov 2006 (PSF)
Python recipes (4591)
Anand's recipes (38)

Required Modules

  • (none specified)

Other Information and Tasks