def genKey(fkey, lkey) : return fkey + chr(lkey + 65) def isChild(father, key) : return key.startswith(father) class Comment : """ This class stores comments and allow the nesting of comment. """ def __init__(self, txt = '', key = '') : self.childs = [] self.content = txt self.key = key def emptyMe(self) : """ Empty the list of comments """ self.childs = [] self.content = '' self._p_changed = 1 def addComment(self, comment, father = None) : """ Add a comment to the list. If father is omitted (or None), the comment is added to the root of the tree. If father is present, the comment is added to the comment with this Id. """ if not father or father == self.key : key = genKey(self.key, len(self.childs)) self.childs.append(Comment(comment, key)) return key else : for i in self.childs : if isChild(i.key, father) : return i.addComment(comment, father) raise 'FatherKeyError', father def flatten(self, level=0) : """ Just a little function to flatten this comment (for use in zpt). Return a liste of tuples. * First element is the nesting level * Second element is the comment. """ val = [] if self.childs : for i in self.childs : val += i.flatten(level + 1) return [(level, self)] + val def __str__(self) : return_val = "" flat = self.flatten() for i in flat : return_val += '%s-> CommentId : %s\n' % (i[0] * ' ', i[1].key) return_val += '%s Comment : %s\n' % (i[0] * ' ', i[1].content) return return_val def __nonzero__(self) : return self.content != '' if __name__ == '__main__' : test = Comment() sId = test.addComment('Salut') oId = test.addComment('Ola') test.addComment('Au revoir', sId) hId = test.addComment('Hasta Luego', oId) test.addComment('Adieu', sId) eId = test.addComment('So long', oId) test.addComment('Anglais', eId) test.addComment('Espagnol', hId) print test try : test.addComment('test', 'C') except 'FatherKeyError', cle : print 'Pas de père appelé %s' % cle