EpicGoodBoi
EpicGoodBoi

Reputation: 170

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.).

Upvotes: 4

Views: 8193

Answers (1)

Bluenix
Bluenix

Reputation: 429

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.
    ...

Upvotes: 5

Related Questions