Warm tip: This article is reproduced from serverfault.com, please click

'ListingGenerator' object is not iterable using ASYNCPRAW

发布于 2021-02-11 19:38:01

I want to get memes from a subreddit. The issue is when I try to get the memes using the method subreddit('memes') the method returns a 'ListingGenerator'object which is not iterable.

I wanted to know if there is any way to convert this into a iterable object or any other method to get memes from reddit using ASYNCPRAW.

Here's the function:

    async def meme(self, ctx):
    subreddit = await  reddit.subreddit('memes')
    print(type(subreddit))
    all_subs = []
    print(subreddit.hot(limit=50))
    for submission in subreddit.hot(limit=50):
        all_subs.append(submission)
    random_sub = random.choice(all_subs)
    name = random_sub.title
    url = random_sub.url
    embed = discord.Embed(title=name)
    embed.set_image(url=url)
    await ctx.send(embed=embed)

This is the error I get:

Traceback (most recent call last):
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
    ret = await coro(*args, **kwargs)
  File "C:\Users\ansel\PycharmProjects\Transfer News\cogs\meme.py", line 48, in meme
    for submission in subreddit.hot(limit=50):
TypeError: 'ListingGenerator' object is not iterable

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 902, in invoke
    await ctx.command.invoke(ctx)
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 864, in invoke
    await injected(*ctx.args, **ctx.kwargs)
  File "C:\Users\ansel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 94, in wrapped
    raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: 'ListingGenerator' object is not iterable
Questioner
Ansel D'souza
Viewed
0
Shunya 2021-02-12 05:53:06

In your meme command you are using a for loop to iterate the returned ListingGenerator, which is an async source. In this case you will need to use an async for loop to be able to iterate an async source.

Using a normal for loop you are not allowed to iterate over an async source unless you try blocking the event loop, because for calls __next__ as a blocking function and does not await its result.

There are some examples of how to iterate over the returned ListingGenerators in APRAW documentation.

References: