Reputation: 574
Is it possible to limit first level comments which replace_more
function returns?
submission.comments.replace_more(limit=1)
Or remove all MoreComments
objects from the first level? I mean I'd like to limit comments tree height
and get maximum width
(get all comments which go from limited amount of the first level comments).
Upvotes: 1
Views: 961
Reputation: 1629
Rather than using replace_more
, just replace each MoreComments
object as you get to it. This will prevent you from replacing any MoreComments
objects that are not at the top level.
Below is a function that will iterate through top-level comments, replacing each MoreComments
as it is encountered. This is inspired by example code from the PRAW documentation:
from praw.models import MoreComments
def iter_top_level(comments):
for top_level_comment in comments:
if isinstance(top_level_comment, MoreComments):
yield from iter_top_level(top_level_comment.comments())
else:
yield top_level_comment
The way this generator works is that it yields top-level comments from the submission, but when it encounters a MoreComments
object, it loads those comments and recursively calls itself. The recursive call is necessary because in large threads, each MoreComments
object contains another top-level MoreComments
object at the end.
Here's an example of how you could use it:
submission = reddit.submission('fgi5bd')
for comment in iter_top_level(submission.comments):
print(comment.author)
Upvotes: 2