Home > OS >  Can I make an asynchoronous method in python?
Can I make an asynchoronous method in python?

Time:08-11

I have started learning about async in python. But in examples, I only see people use async keyword in functions. I wonder if I can use it with methods?

Here is what I tried:

import asyncio

class asyncClass:
    async def asyncMethod(self):
        print("Starting")
        await asyncio.sleep(1)
        print("Ending!")
class1 = asyncClass()
class1.asyncMethod()

But I got this error:

RuntimeWarning: coroutine 'asyncClass.asyncMethod' was never awaited
  class1.asyncMethod()
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

I haven't figured out why this error happened because I already put await keyword into the method.

CodePudding user response:

You need to use asyncio.run to execute the method: asyncio.run(class1.asyncMethod())

  • Related