composite.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  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 provides methods
  7. to add/access/modify children by name, like a Composite.
  8. Created Anand B Pillai <abpillai@gmail.com>
  9. """
  10. __author__ = "Anand B Pillai"
  11. __maintainer__ = "Anand B Pillai"
  12. __version__ = "0.2"
  13. def normalize(val):
  14. """Normalize a string so that it can be used as an attribute to a Python
  15. object
  16. """
  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 access to its keys """
  27. def __getattr__(self, name):
  28. if name in self.__dict__:
  29. return self.__dict__[name]
  30. elif name in self:
  31. return self.get(name)
  32. else:
  33. # Check for denormalized name
  34. name = denormalize(name)
  35. if name in self:
  36. return self.get(name)
  37. else:
  38. raise AttributeError('no attribute named %s' % name)
  39. def __setattr__(self, name, value):
  40. if name in self.__dict__:
  41. self.__dict__[name] = value
  42. elif name in self:
  43. self[name] = value
  44. else:
  45. # Check for denormalized name
  46. name2 = denormalize(name)
  47. if name2 in self:
  48. self[name2] = value
  49. else:
  50. # New attribute
  51. self[name] = value
  52. class CompositeDict(SpecialDict):
  53. """ A class which works like a hierarchical dictionary.
  54. This class is based on the Composite design-pattern """
  55. ID = 0
  56. def __init__(self, name=''):
  57. if name:
  58. self._name = name
  59. else:
  60. self._name = ''.join(('id#', str(self.__class__.ID)))
  61. self.__class__.ID += 1
  62. self._children = []
  63. # Link back to father
  64. self._father = None
  65. self[self._name] = SpecialDict()
  66. def __getattr__(self, name):
  67. if name in self.__dict__:
  68. return self.__dict__[name]
  69. elif name in self:
  70. return self.get(name)
  71. else:
  72. # Check for denormalized name
  73. name = denormalize(name)
  74. if name in self:
  75. return self.get(name)
  76. else:
  77. # Look in children list
  78. child = self.findChild(name)
  79. if child:
  80. return child
  81. else:
  82. attr = getattr(self[self._name], name)
  83. if attr:
  84. return attr
  85. raise AttributeError('no attribute named %s' % name)
  86. def isRoot(self):
  87. """ Return whether I am a root component or not """
  88. # If I don't have a parent, I am root
  89. return not self._father
  90. def isLeaf(self):
  91. """ Return whether I am a leaf component or not """
  92. # I am a leaf if I have no children
  93. return not self._children
  94. def getName(self):
  95. """ Return the name of this ConfigInfo object """
  96. return self._name
  97. def getIndex(self, child):
  98. """ Return the index of the child ConfigInfo object 'child' """
  99. if child in self._children:
  100. return self._children.index(child)
  101. else:
  102. return -1
  103. def getDict(self):
  104. """ Return the contained dictionary """
  105. return self[self._name]
  106. def getProperty(self, child, key):
  107. """Return the value for the property for child '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 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)
  245. ### OUTPUT ###
  246. # Submit
  247. # Browse