Mark
Mark

Reputation: 81

On Python Asyncio I am trying to return a value from one function to another

On Python Asyncio I am trying to return a value from one function to another .

So when the if statement in the end of func "check" is True the returned will value

will go the the "print" func .

async def check(i):
        async with aiohttp.ClientSession() as session:
            url = f'https://pokeapi.co/api/v2/pokemon/{i}'
            async with session.get(url) as resp:
                data = await resp.text()
                if data['state'] == 'yes':
                    return data['state']
                ## how do i keeping the structre of the asyncio and pass this result to the "print" function



async def print(here should be the return of "check" funtion is there is):
        print()
        await asyncio.sleep(0)


async def main():
    for i in range(0,5):
        await asyncio.gather(check(i),
                             print() )

Thank You (-:

Upvotes: 0

Views: 1247

Answers (2)

dirn
dirn

Reputation: 20729

Your code is going to run everything synchronously. You need to restructure things a bit to see any value from asyncio.

async def check(i):
    async with aiohttp.ClientSession() as session:
        url = f'https://pokeapi.co/api/v2/pokemon/{i}'
        async with session.get(url) as resp:
            data = await resp.text()
            if data['state'] == 'yes':
                return data['state']

async def main():
    aws = [check(i) for i in range(5)]
    results = await asyncio.gather(*aws)
    for result in results:
        print(result)

This will allow your aiohttp requests to run asynchronously. Assuming print is really just a wrapper around the builtin, you don't need it and can just use the builtin.

If, however, print actually does something else, you should use asyncio.as_completed instead of asyncio.gather.

async def my_print(result):
    print(result)
    await asyncio.sleep(0)

async def main():
    aws = [check(i) for i in range(5)]
    for coro in asyncio.as_completed(aws):
        result = await coro
        await my_print(result)

Upvotes: 2

VPfB
VPfB

Reputation: 17247

Simple solution: do not run the two functions concurrently. One of them clearly needs the other to finish.

async def print_it(i):
    value = await check(i)
    if value is not None:
        print(value)

There is an implicit return None when a function finishes its last statement, i.e. when return data['state'] is NOT executed in check(). In that case nothing is printed - adjust the code if that is not correct.

Of course, you should start only print_it coroutines, without starting checks.


If you really need to run the functions concurrently for some reason, use a Queue. The producer puts the data into the queue, the consument gets the value when it is available.

Upvotes: 1

Related Questions