Use asyncio methods on tornado's ioloop (such as create_future)

1.8k Views Asked by At

I am aware that since 5.0 tornado's ioloop is handled by asyncio and in fact the loop I get using tornado.ioloop.IOloop.current() is an asyncio loop by default. My question is how do I access the asyncio loop itself in a proper way. For example I would like to use the loop.create_future() method on the asyncio loop, but tornado wraps the loop and it doesn't have this method on it.

Currently what I do is when I need asyncio methods I just call asyncio.get_event_loop() (because the documentation states that the two loops are indeed identical). I am not sure this is the correct way of doing this since now I have different references to the same ioloop with different interfaces and I use the one that is needed. This is kind of messy and confusing.

Is there a better way? Can I tell tornado to give me the asyncio loop without wrapping it? Or can I access these methods somehow using the IOloop that tornado creates?

EDIT:

https://www.tornadoweb.org/en/stable/ioloop.html#module-tornado.ioloop Here it states the following:

Applications can use either the IOLoop interface or the underlying asyncio event loop directly

I am interested in the latter, yet I can’t find instructions on how to access it directly.

2

There are 2 best solutions below

2
Ben Darnell On BEST ANSWER

asyncio.get_event_loop() is the recommended method; no need to use the (undocumented) asyncio_loop attribute. This is how all non-tornado-specific asyncio code gets the event loop.

0
MrBlaise On

I finally found a way. So the ioloop that tornado creates will be of type AsyncIOMainLoop. I went to the source code and its base class is BaseAsyncIOLoop in that class there is a property called asyncio_loop

With that I was finally able to use asyncio loop. (ioloop.IOLoop.current().asyncio_loop)