composite.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  1. """
  2. A class which defines a composite object which can store
  3. hieararchical dictionaries with names.
  4. This class is same as a hiearchical dictionary, but it
  5. provides methods to add/access/modify children by name,
  6. like a Composite.
  7. Created Anand B Pillai <abpillai@gmail.com>
  8. """
  9. __author__ = "Anand B Pillai"
  10. __maintainer__ = "Anand B Pillai"
  11. __version__ = "0.2"
  12. def normalize(val):
  13. """ Normalize a string so that it can be used as an attribute
  14. to a Python object """
  15. if val.find('-') != -1:
  16. val = val.replace('-','_')
  17. return val
  18. def denormalize(val):
  19. """ De-normalize a string """
  20. if val.find('_') != -1:
  21. val = val.replace('_','-')
  22. return val
  23. class SpecialDict(dict):
  24. """ A dictionary type which allows direct attribute
  25. access to its keys """
  26. def __getattr__(self, name):
  27. if name in self.__dict__:
  28. return self.__dict__[name]
  29. elif name in self:
  30. return self.get(name)
  31. else:
  32. # Check for denormalized name
  33. name = denormalize(name)
  34. if name in self:
  35. return self.get(name)
  36. else:
  37. raise AttributeError('no attribute named %s' % name)
  38. def __setattr__(self, name, value):
  39. if name in self.__dict__:
  40. self.__dict__[name] = value
  41. elif name in self:
  42. self[name] = value
  43. else:
  44. # Check for denormalized name
  45. name2 = denormalize(name)
  46. if name2 in self:
  47. self[name2] = value
  48. else:
  49. # New attribute
  50. self[name] = value
  51. class CompositeDict(SpecialDict):
  52. """ A class which works like a hierarchical dictionary.
  53. This class is based on the Composite design-pattern """
  54. ID = 0
  55. def __init__(self, name=''):
  56. if name:
  57. self._name = name
  58. else:
  59. self._name = ''.join(('id#',str(self.__class__.ID)))
  60. self.__class__.ID += 1
  61. self._children = []
  62. # Link back to father
  63. self._father = None
  64. self[self._name] = SpecialDict()
  65. def __getattr__(self, name):
  66. if name in self.__dict__:
  67. return self.__dict__[name]
  68. elif name in self:
  69. return self.get(name)
  70. else:
  71. # Check for denormalized name
  72. name = denormalize(name)
  73. if name in self:
  74. return self.get(name)
  75. else:
  76. # Look in children list
  77. child = self.findChild(name)
  78. if child:
  79. return child
  80. else:
  81. attr = getattr(self[self._name], name)
  82. if attr: return attr
  83. raise AttributeError('no attribute named %s' % name)
  84. def isRoot(self):
  85. """ Return whether I am a root component or not """
  86. # If I don't have a parent, I am root
  87. return not self._father
  88. def isLeaf(self):
  89. """ Return whether I am a leaf component or not """
  90. # I am a leaf if I have no children
  91. return not self._children
  92. def getName(self):
  93. """ Return the name of this ConfigInfo object """
  94. return self._name
  95. def getIndex(self, child):
  96. """ Return the index of the child ConfigInfo object 'child' """
  97. if child in self._children:
  98. return self._children.index(child)
  99. else:
  100. return -1
  101. def getDict(self):
  102. """ Return the contained dictionary """
  103. return self[self._name]
  104. def getProperty(self, child, key):
  105. """ Return the value for the property for child
  106. 'child' with key 'key' """
  107. # First get the child's dictionary
  108. childDict = self.getInfoDict(child)
  109. if childDict:
  110. return childDict.get(key, None)
  111. def setProperty(self, child, key, value):
  112. """ Set the value for the property 'key' for
  113. the child 'child' to 'value' """
  114. # First get the child's dictionary
  115. childDict = self.getInfoDict(child)
  116. if childDict:
  117. childDict[key] = value
  118. def getChildren(self):
  119. """ Return the list of immediate children of this object """
  120. return self._children
  121. def getAllChildren(self):
  122. """ Return the list of all children of this object """
  123. l = []
  124. for child in self._children:
  125. l.append(child)
  126. l.extend(child.getAllChildren())
  127. return l
  128. def getChild(self, name):
  129. """ Return the immediate child object with the given name """
  130. for child in self._children:
  131. if child.getName() == name:
  132. return child
  133. def findChild(self, name):
  134. """ Return the child with the given name from the tree """
  135. # Note - this returns the first child of the given name
  136. # any other children with similar names down the tree
  137. # is not considered.
  138. for child in self.getAllChildren():
  139. if child.getName() == name:
  140. return child
  141. def findChildren(self, name):
  142. """ Return a list of children with the given name from the tree """
  143. # Note: this returns a list of all the children of a given
  144. # name, irrespective of the depth of look-up.
  145. children = []
  146. for child in self.getAllChildren():
  147. if child.getName() == name:
  148. children.append(child)
  149. return children
  150. def getPropertyDict(self):
  151. """ Return the property dictionary """
  152. d = self.getChild('__properties')
  153. if d:
  154. return d.getDict()
  155. else:
  156. return {}
  157. def getParent(self):
  158. """ Return the person who created me """
  159. return self._father
  160. def __setChildDict(self, child):
  161. """ Private method to set the dictionary of the child
  162. object 'child' in the internal dictionary """
  163. d = self[self._name]
  164. d[child.getName()] = child.getDict()
  165. def setParent(self, father):
  166. """ Set the parent object of myself """
  167. # This should be ideally called only once
  168. # by the father when creating the child :-)
  169. # though it is possible to change parenthood
  170. # when a new child is adopted in the place
  171. # of an existing one - in that case the existing
  172. # child is orphaned - see addChild and addChild2
  173. # methods !
  174. self._father = father
  175. def setName(self, name):
  176. """ Set the name of this ConfigInfo object to 'name' """
  177. self._name = name
  178. def setDict(self, d):
  179. """ Set the contained dictionary """
  180. self[self._name] = d.copy()
  181. def setAttribute(self, name, value):
  182. """ Set a name value pair in the contained dictionary """
  183. self[self._name][name] = value
  184. def getAttribute(self, name):
  185. """ Return value of an attribute from the contained dictionary """
  186. return self[self._name][name]
  187. def addChild(self, name, force=False):
  188. """ Add a new child 'child' with the name 'name'.
  189. If the optional flag 'force' is set to True, the
  190. child object is overwritten if it is already there.
  191. This function returns the child object, whether
  192. new or existing """
  193. if type(name) != str:
  194. raise ValueError('Argument should be a string!')
  195. child = self.getChild(name)
  196. if child:
  197. # print 'Child %s present!' % name
  198. # Replace it if force==True
  199. if force:
  200. index = self.getIndex(child)
  201. if index != -1:
  202. child = self.__class__(name)
  203. self._children[index] = child
  204. child.setParent(self)
  205. self.__setChildDict(child)
  206. return child
  207. else:
  208. child = self.__class__(name)
  209. child.setParent(self)
  210. self._children.append(child)
  211. self.__setChildDict(child)
  212. return child
  213. def addChild2(self, child):
  214. """ Add the child object 'child'. If it is already present,
  215. it is overwritten by default """
  216. currChild = self.getChild(child.getName())
  217. if currChild:
  218. index = self.getIndex(currChild)
  219. if index != -1:
  220. self._children[index] = child
  221. child.setParent(self)
  222. # Unset the existing child's parent
  223. currChild.setParent(None)
  224. del currChild
  225. self.__setChildDict(child)
  226. else:
  227. child.setParent(self)
  228. self._children.append(child)
  229. self.__setChildDict(child)
  230. if __name__=="__main__":
  231. window = CompositeDict('Window')
  232. frame = window.addChild('Frame')
  233. tfield = frame.addChild('Text Field')
  234. tfield.setAttribute('size','20')
  235. btn = frame.addChild('Button1')
  236. btn.setAttribute('label','Submit')
  237. btn = frame.addChild('Button2')
  238. btn.setAttribute('label','Browse')
  239. # print(window)
  240. # print(window.Frame)
  241. # print(window.Frame.Button1)
  242. # print(window.Frame.Button2)
  243. print(window.Frame.Button1.label)
  244. print(window.Frame.Button2.label)