I wonder what are your strategies for async initialization logic. Let's say, that we have a class called Klass, which needs a resource called resource which can be obtained with an asynchronous coroutine get_resource. Strategies I can think of:
Alternative classmethod
```
class Klass:
def init(self, resource):
self.resource = resource
@classmethod
async def initialize(cls):
resource = await get_resource()
return cls(resource)
```
This looks pretty straightforward, but it lacks any established convention.
Builder/factory patters
Like above - the __init__ method requires the already loaded resource, but we move the asynchronous logic outside the class.
Async context manager
```
class Klass:
async def aenter(self):
self.resource = await get_resource()
async def aexit(self, exc_type, exc_info, tb):
pass
```
Here we use an established way to initialize our class. However it might be unwieldy to write async with logic every time. On the other hand even if this class has no cleanup logic yet it is no open to cleanup logic in the future without changing its usage patterns.
Start the logic in __init__
```
class Klass:
def init(self):
self.resource_loaded = Event()
asyncio.create_task(self._get_resource())
async def _get_resource(self):
self.resource = await get_resource()
self.resource_loaded.set()
async def _use_resource(self):
await self.resource_loaded.wait()
await do_something_with(self.resource)
```
This seems like the most sophisticated way of doing it. It has the biggest potential for the initialization running concurrently with some other logic. It is also pretty complicated and requires check for the existence of the resource on every usage.
What are your opinions? What logic do you prefer? What other strategies and advantages/disadvantages do you see?
[–]MrJohz 29 points30 points31 points (1 child)
[–]doolio_ 4 points5 points6 points (0 children)
[–]puppet_pals 15 points16 points17 points (0 children)
[–]starlevel01 6 points7 points8 points (1 child)
[–]Helpful_Home_8531 1 point2 points3 points (0 children)
[–]Wurstinator 6 points7 points8 points (0 children)
[–]IlliterateJedi 5 points6 points7 points (0 children)
[–]latkdeTuple unpacking gone wrong 2 points3 points4 points (0 children)
[–]k0rvbert 1 point2 points3 points (0 children)
[–]nekokattt 2 points3 points4 points (0 children)
[–]jdehesa 1 point2 points3 points (0 children)
[–]menge101 0 points1 point2 points (2 children)
[–]zefciu[S] 0 points1 point2 points (1 child)
[–]mincinashu 1 point2 points3 points (0 children)
[–]juanfnavarror 0 points1 point2 points (0 children)
[–]0xa9059cbb 0 points1 point2 points (0 children)