composite.py 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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:
  83. return attr
  84. raise AttributeError('no attribute named %s' % name)
  85. def isRoot(self):
  86. """ Return whether I am a root component or not """
  87. # If I don't have a parent, I am root
  88. return not self._father
  89. def isLeaf(self):
  90. """ Return whether I am a leaf component or not """
  91. # I am a leaf if I have no children
  92. return not self._children
  93. def getName(self):
  94. """ Return the name of this ConfigInfo object """
  95. return self._name
  96. def getIndex(self, child):
  97. """ Return the index of the child ConfigInfo object 'child' """
  98. if child in self._children:
  99. return self._children.index(child)
  100. else:
  101. return -1
  102. def getDict(self):
  103. """ Return the contained dictionary """
  104. return self[self._name]
  105. def getProperty(self, child, key):
  106. """ Return the value for the property for child
  107. 'child' with key 'key' """
  108. # First get the child's dictionary
  109. childDict = self.getInfoDict(child)
  110. if childDict:
  111. return childDict.get(key, None)
  112. def setProperty(self, child, key, value):
  113. """ Set the value for the property 'key' for
  114. the child 'child' to 'value' """
  115. # First get the child's dictionary
  116. childDict = self.getInfoDict(child)
  117. if childDict:
  118. childDict[key] = value
  119. def getChildren(self):
  120. """ Return the list of immediate children of this object """
  121. return self._children
  122. def getAllChildren(self):
  123. """ Return the list of all children of this object """
  124. l = []
  125. for child in self._children:
  126. l.append(child)
  127. l.extend(child.getAllChildren())
  128. return l
  129. def getChild(self, name):
  130. """ Return the immediate child object with the given name """
  131. for child in self._children:
  132. if child.getName() == name:
  133. return child
  134. def findChild(self, name):
  135. """ Return the child with the given name from the tree """
  136. # Note - this returns the first child of the given name
  137. # any other children with similar names down the tree
  138. # is not considered.
  139. for child in self.getAllChildren():
  140. if child.getName() == name:
  141. return child
  142. def findChildren(self, name):
  143. """ Return a list of children with the given name from the tree """
  144. # Note: this returns a list of all the children of a given
  145. # name, irrespective of the depth of look-up.
  146. children = []
  147. for child in self.getAllChildren():
  148. if child.getName() == name:
  149. children.append(child)
  150. return children
  151. def getPropertyDict(self):
  152. """ Return the property dictionary """
  153. d = self.getChild('__properties')
  154. if d:
  155. return d.getDict()
  156. else:
  157. return {}
  158. def getParent(self):
  159. """ Return the person who created me """
  160. return self._father
  161. def __setChildDict(self, child):
  162. """ Private method to set the dictionary of the child
  163. object 'child' in the internal dictionary """
  164. d = self[self._name]
  165. d[child.getName()] = child.getDict()
  166. def setParent(self, father):
  167. """ Set the parent object of myself """
  168. # This should be ideally called only once
  169. # by the father when creating the child :-)
  170. # though it is possible to change parenthood
  171. # when a new child is adopted in the place
  172. # of an existing one - in that case the existing
  173. # child is orphaned - see addChild and addChild2
  174. # methods !
  175. self._father = father
  176. def setName(self, name):
  177. """ Set the name of this ConfigInfo object to 'name' """
  178. self._name = name
  179. def setDict(self, d):
  180. """ Set the contained dictionary """
  181. self[self._name] = d.copy()
  182. def setAttribute(self, name, value):
  183. """ Set a name value pair in the contained dictionary """
  184. self[self._name][name] = value
  185. def getAttribute(self, name):
  186. """ Return value of an attribute from the contained dictionary """
  187. return self[self._name][name]
  188. def addChild(self, name, force=False):
  189. """ Add a new child 'child' with the name 'name'.
  190. If the optional flag 'force' is set to True, the
  191. child object is overwritten if it is already there.
  192. This function returns the child object, whether
  193. new or existing """
  194. if type(name) != str:
  195. raise ValueError('Argument should be a string!')
  196. child = self.getChild(name)
  197. if child:
  198. # print 'Child %s present!' % name
  199. # Replace it if force==True
  200. if force:
  201. index = self.getIndex(child)
  202. if index != -1:
  203. child = self.__class__(name)
  204. self._children[index] = child
  205. child.setParent(self)
  206. self.__setChildDict(child)
  207. return child
  208. else:
  209. child = self.__class__(name)
  210. child.setParent(self)
  211. self._children.append(child)
  212. self.__setChildDict(child)
  213. return child
  214. def addChild2(self, child):
  215. """ Add the child object 'child'. If it is already present,
  216. it is overwritten by default """
  217. currChild = self.getChild(child.getName())
  218. if currChild:
  219. index = self.getIndex(currChild)
  220. if index != -1:
  221. self._children[index] = child
  222. child.setParent(self)
  223. # Unset the existing child's parent
  224. currChild.setParent(None)
  225. del currChild
  226. self.__setChildDict(child)
  227. else:
  228. child.setParent(self)
  229. self._children.append(child)
  230. self.__setChildDict(child)
  231. if __name__ == "__main__":
  232. window = CompositeDict('Window')
  233. frame = window.addChild('Frame')
  234. tfield = frame.addChild('Text Field')
  235. tfield.setAttribute('size', '20')
  236. btn = frame.addChild('Button1')
  237. btn.setAttribute('label', 'Submit')
  238. btn = frame.addChild('Button2')
  239. btn.setAttribute('label', 'Browse')
  240. # print(window)
  241. # print(window.Frame)
  242. # print(window.Frame.Button1)
  243. # print(window.Frame.Button2)
  244. print(window.Frame.Button1.label)
  245. print(window.Frame.Button2.label)