Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python | AsyncIO | TypeError: a coroutine was expected

I'm trying python coroutine programming using asyncio. This is my code.

import asyncio

async def coro_function():
    return 2 + 2

async def get():
    return await coro_function()

print(asyncio.iscoroutinefunction(get))

loop = asyncio.get_event_loop()
a1 = loop.create_task(get)
loop.run_until_complete(a1)

But when I execute it, it gives me error

True
Traceback (most recent call last):
  File "a.py", line 13, in <module>
    a1 = loop.create_task(get)
  File "/home/alie/anaconda3/lib/python3.7/asyncio/base_events.py", line 405, in create_task
    task = tasks.Task(coro, loop=self)
TypeError: a coroutine was expected, got <function get at 0x7fe1280b6c80>

How to solve it?

like image 511
Chidananda Nayak Avatar asked Nov 28 '25 14:11

Chidananda Nayak


2 Answers

You're passing in the function get.

In order to pass in a coroutine, pass in get().

a1 = loop.create_task(get())
loop.run_until_complete(a1)

Take a look at the types:

>>> type(get)
<class 'function'>
>>> print(type(get()))
<class 'coroutine'>

get is a coroutine function, i.e. a function that returns a coroutine object, get(). For more information and a better understanding of the fundamentals, take a look at the docs.

like image 187
Algebra8 Avatar answered Nov 30 '25 04:11

Algebra8


Here is an example of code that can help you:

import asyncio

sync def coro_function():
        return 2 + 2

def async execute():
    async with asyncio.TaskGroup() as group:
         group.create_task(coro_function())
    
asyncio.run(execute())
    
like image 29
Yablai Bougouyou Avatar answered Nov 30 '25 04:11

Yablai Bougouyou



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!