Nikita Davydov
Nikita Davydov

Reputation: 957

Python, Async, singleton event loop

I have a lot of async code and I have the question.

May I have a singleton event loop in the whole project or I should use get_event_loop() in every function, method, class? Are there some problems to declare it one time and use it from any place in the project?

For example, I have 3 files app.py, views.py, internal.py

app.py

app = FastAPI()
loop = get_event_loop()

views.py

from app import app, loop

@app.get('/')
async def main(request):
   loop.create_task(<any coroutine>)
   return {'status': 'ok'}

internal.py

from app import loop

async def any_buisiness_logic():
    loop.create_task(<any coroutine>)
    return "task created"

Or I should get_event_loop() in every file?

Upvotes: 0

Views: 2491

Answers (1)

Uku Loskit
Uku Loskit

Reputation: 42040

You can use asyncio.create_task instead. Loop needn't be passed around in newer versions of Python.

The task is executed in the loop returned by get_running_loop(), RuntimeError is raised if there is no running loop in current thread.

https://docs.python.org/3/library/asyncio-task.html#asyncio.create_task

Upvotes: 3

Related Questions