1

I'm having issues where my call to api.say() fails. I understand its a coroutine and needs to be yielded from but is that valid if my print_all is a standard function.

What is the correct way to structure this example?

Please assume that the Client isn't changeable, only the code in my example.

from .client import Client
import asyncio

api = Client()
login = ('', '')

def print_all(b=None, m=None):
    print("Buffer!", b)
    print("Message", m)

    if b and m:
        if b.name == 'bat':
            print("-sending to", b)
            api.say(b, "Hey yo."):    # <----


def main():
    api.login(*login)
    api.register_message_callback(print_all)
    api.register_state_callback(print_all)

    loop = asyncio.get_event_loop()
    loop.run_until_complete(api.run())
    loop.close()

if __name__ == '__main__':
    main()

1 Answer 1

1

The Client API might handle callbacks that are coroutines too i.e., you can convert print_all() into a coroutine (prepend async before def, add await before api.say()).

Otherwise, you could call asyncio.ensure_future(api.say(..)) to schedule the coroutine. It assumes that loop.run_until_complete(api.run()) won't return before api.say() is done i.e., there is loop.run_forever() equivalent in your program or you wait for all tasks -- either collected explicitly or implicitly (asyncio.Task.all_tasks()).

1
  • Thanks asyncio.ensure_future(api.say(..)) fixed the issue. My client didn't handle the callbacks as coroutines so .ensure_future(...) sorted it out.
    – PsyKzz
    Jan 7, 2016 at 11:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.