composite.py 9.2 KB

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