5

Generator-based coroutines can be easily created from function object:

coro = asyncio.coroutine(func)

What about native coroutines (which usually creates by async def)?
Is there any way to create them from existing function objects?

Mikhail Gerasimov
  • 36,989
  • 16
  • 116
  • 159

1 Answers1

1

In Python 3.5 the way to create an async function is by using the async def() syntax. Not sure of the benefit of trying to wrap a normal function into a native coroutine because if there is nothing to await, it would seem pointless? Especially since there is no need to call the function using await or yield from? (Since you can just execute it normally.)

Nevertheless, would this work for your purposes?

def test():
    print('boo')

async def async_test():
    return test()
songololo
  • 4,724
  • 5
  • 35
  • 49
  • 1
    Benefit to wrap in special cases, when we can't define function as coroutine, but we need to use it as coroutine. Better to see: http://stackoverflow.com/a/23036785/1113207 – Mikhail Gerasimov Oct 28 '15 at 17:49
  • Do you have a specific example of a use case? – songololo Oct 28 '15 at 21:21
  • I don't follow the use case also. – Andrew Svetlov Oct 29 '15 at 00:00
  • 1
    You're right. I just understood, I really don't need it. – Mikhail Gerasimov Oct 29 '15 at 03:20
  • 1
    For the record, I have a use case. I have a rogue task creation somewhere I want to find, so I'd like to wrap the existing code in a coroutine and return that from a normal function, which would then allow me to call `traceback.print_stack()` before returning the coroutine. `asyncio.coroutine(func)` worked, though. Just... you have to convert every await inside the function or comment them out. – Randelung Apr 05 '22 at 15:39