In class Wizard, I would like to set attribute wand to the value returned by coroutine magic.
class Wizard:
async def acquire_wand(self):
self.wand = await magic()
This code is considered "bad Python", however, because wand is not defined in __init__. I cannot define it in __init__, though, because await may only be used in asynchronous functions.
class Wizard:
def __init__(self):
self.wand = None
async def acquire_wand(self):
self.wand = await magic()
async def perform_spell(self):
if self.wand is None:
await self.acquire_wand()
self.wand.wave()
I could set wand to None in __init__ and use if self.wand is None: wherever it is accessed, but this seems messy and unwieldy.
How can I ensure that wand is defined throughout the class?