13 ms·
Here's a use case - singleton instantiation on first request, where instantiation itself requires an async call (eg: to DB or external service). _lock = as
by never_inline 10mo ago
Here's a use case - singleton instantiation on first request, where instantiation itself requires an async call (eg: to DB or external service).
_lock = asyncio.Lock()
_instance = None
def get_singleton():
if _instance:
return _instance
async with _lock:
if not _instance:
_instance = await costly_function()
return _instance
How do you suggest to replace this?
- duped 10mo agoThe traditional thing would be to have an init() function that is required to be called at the top of main() or before any other methods that need it. But I agree with your point.
- never_inline 10mo agoNow lets say its an async cache instead of singleton.
- duped 10mo agoReturn the cached item if it exists else spawn a task to update it (doing nothing if the task has already been spawned), await the task and return the cached item.
- never_inline 10mo agoThanks, that's a useful trick.