Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async Python - How to make a class __init__ run async functions within the class __init__

Let's say I have this:

class Test():
    def __init__(self, number):
        self.number = number
        await self.TestPrint()

    async def TestPrint(self):
        print(self.number)

As you can see this won't work since __init__ is not async and I cannot call await for the function.

I want to be able to run TestPrint within __init__ assuming I want to maintain this function async.

I also want this to have nothing to do with anything else other than the class (other function, other classes, main, etc.).

like image 871
EpicGoodBoi Avatar asked Sep 12 '25 19:09

EpicGoodBoi


1 Answers

Like chepner mentioned in the comments:

An asynchronous class method that creates the object and then calls the TestPrint method before returning it sounds more appropriate.

This is the preferred way above all else and why a lot of there are a lot of functions that initialize internal asyncio classes rather than you directly instantiating them.

That said, if you wish to have this close to the class you can use a @classmethod which can be async. Your code would look like this:

class Test():
    def __init__(self, number):
        self.number = number

    async def TestPrint(self):
            print(self.number)

    @classmethod
    async def with_print(cls, number):
        self = cls(number)
        await self.TestPrint()
        return self
async def main():
    t = await Test.with_print(123)
    # 't' is now your Test instance.
    ...
like image 157
Bluenix Avatar answered Sep 15 '25 20:09

Bluenix