So... you've got something like this?
class Comment(object):
all_comments = []
def __init__(self, message, parent):
self.message = message
self.parent = parent
self.all_comments.append(self)
def __iter__(self):
"""
Yields tuples of (indentation level, comments), with this comment first
and child comments later.
"""
# what goes here?
This just a depth-first pre-order tree traversal.
import itertools
class Comment(object):
def __iter__(self):
return _iter_helper(self, 0)
def _iter_helper(self, depth):
item = {'indent_level': depth, 'comment': self}
return itertools.chain([item],
*[comment._iter_helper(depth+1)
for comment
in self.all_comments
if comment.parent == self])
As Harypyon suggests, storing the children is a more efficient way of viewing this problem than storing the parent and then computing the children.
EDIT:
I don't think storing children is possible with MySQL.
Ok.. this is in a database and you (probably) want some SQL that produces the desired result?
You've got a table like something like this?
CREATE TABLE comments (
id INTEGER PRIMARY KEY,
parent INTEGER,
comment TEXT
);
Unfortunately, MySQL doesn't support recursive query syntac (neither the with recursive common table expressions nor connect by), so this self referential schema, though simple and elegant, is not useful if you want to do the whole thing in a single query with arbitrary depth and all of the needed metadata.
There are two solutions. First, you can emulate the recursive query by doing the equivalent of a common table query in python, or in MySQL using temporary tables, with each of the sub-selects as a separate actual query. The downside is that this is neither elegant (many sql queries) and wasteful, (extra data transmitted over the connection or stored on disk).
Another option is to is accept that the transitive closure of the tree of comments is simply not computable, but that you can still make do with a compromise. You most likely don't want (or need) to show more than a hundred comments at a time, and you similarly don't need to show a depth of more than, say, 5 levels of nesting. To get more information, you would Just run the same query with a different root comment. Thus, you end up with a query something like
SELECT c1.*, c2.*, c3.*, c4.*, c5.*
FROM comments c1
LEFT JOIN comments c2 ON c1.id = c2.parent
LEFT JOIN comments c3 ON c2.id = c3.parent
LEFT JOIN comments c4 ON c3.id = c4.parent
LEFT JOIN comments c5 ON c4.id = c5.parent
WHERE c1.parent = ?
Which will give you a good "batch" of comments, up to 5 levels deep.