lu3si
lu3si

Reputation: 327

how get I a return value from a gather method

I want to have the return value of the task_2 function, but it doesn't work the way I want it to. Actually, I want the return from the task_2 function as a usable value in the main function so that I could use it for another function

class test_class():
    def __init__(self):
        self.list_el = [1,2,3,4,5,6]
        self.loop = asyncio.get_event_loop()


    def main(self):
        return_value = self.loop_1()
        print(return_value)

    def loop_1(self):
        output = self.loop.run_until_complete(self.task_1())
        return output

    async def task_1(self):
        tasks = []
        for i in self.list_el:
            tasks.append(asyncio.create_task(self.task_2(i)))
        return tasks

    async def task_2(self,number):
        odd = []
        even = []
        if number % 2 ==0:
            print("even")
            even.append(number)
        else:
            print("odd")
            odd.append(number)

        return even,odd

if __name__ == "__main__":
    app =test_class()
    app.main()

Upvotes: 0

Views: 83

Answers (1)

larsks
larsks

Reputation: 312138

The return value from from self.loop_1() is already contains everything you need. If you look at the output from your program, you see that print(return_value) prints something like:

[<Task finished name='Task-2' coro=<test_class.task_2() done, defined at /home/lars/tmp/python/astest.py:27> result=([], [1])>, <Task finished name='Task-3' coro=<test_class.task_2() done, defined at /home/lars/tmp/python/astest.py:27> result=([2], [])>,...]

Looking at one of those values, we see:

<Task finished name='Task-2' coro=<test_class.task_2() done,
defined at /home/lars/tmp/python/astest.py:27> 
result=([], [1])>

You can see the value you want in the result attribute. So you just need to iterate over the returned Task objects and get the result from each one:

import asyncio


class test_class:
    def __init__(self):
        self.list_el = [1, 2, 3, 4, 5, 6]

    def main(self):
        return_value = self.loop_1()
        for task in return_value:
            odd, even = task.result()
            print(f"odd {odd} even {even}")

    def loop_1(self):
        loop = asyncio.get_event_loop()
        output = loop.run_until_complete(self.task_1())
        return output

    async def task_1(self):
        tasks = []
        for i in self.list_el:
            tasks.append(asyncio.create_task(self.task_2(i)))
        return tasks

    async def task_2(self, number):
        odd = []
        even = []
        if number % 2 == 0:
            print("even")
            even.append(number)
        else:
            print("odd")
            odd.append(number)

        return even, odd


if __name__ == "__main__":
    app = test_class()
    app.main()

Upvotes: 1

Related Questions