### Navigation
- [index](# "General Index")
- [modules](# "Python Module Index") |
- [next](# "tornado.concurrent — Work with threads and futures") |
- [previous](# "Coroutines and concurrency") |
- [Tornado 4.4.dev1 documentation](#) »
- [Coroutines and concurrency](#) »
# `tornado.gen` — Simplify asynchronous code
`tornado.gen` is a generator-based interface to make it easier towork in an asynchronous environment. Code using the `gen` moduleis technically asynchronous, but it is written as a single generatorinstead of a collection of separate functions.
For example, the following asynchronous handler:
~~~
class AsyncHandler(RequestHandler):
@asynchronous
def get(self):
http_client = AsyncHTTPClient()
http_client.fetch("http://example.com",
callback=self.on_fetch)
def on_fetch(self, response):
do_something_with_response(response)
self.render("template.html")
~~~
could be written with `gen` as:
~~~
class GenAsyncHandler(RequestHandler):
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response = yield http_client.fetch("http://example.com")
do_something_with_response(response)
self.render("template.html")
~~~
Most asynchronous functions in Tornado return a [`Future`](# "tornado.concurrent.Future");yielding this object returns its [`result`](# "tornado.concurrent.Future.result").
You can also yield a list or dict of `Futures`, which will bestarted at the same time and run in parallel; a list or dict of results willbe returned when they are all finished:
~~~
@gen.coroutine
def get(self):
http_client = AsyncHTTPClient()
response1, response2 = yield [http_client.fetch(url1),
http_client.fetch(url2)]
response_dict = yield dict(response3=http_client.fetch(url3),
response4=http_client.fetch(url4))
response3 = response_dict['response3']
response4 = response_dict['response4']
~~~
If the [`singledispatch`](https://docs.python.org/3.4/library/functools.html#functools.singledispatch "(in Python v3.4)") [https://docs.python.org/3.4/library/functools.html#functools.singledispatch] library is available (standard inPython 3.4, available via the [singledispatch](https://pypi.python.org/pypi/singledispatch) [https://pypi.python.org/pypi/singledispatch] package on olderversions), additional types of objects may be yielded. Tornado includessupport for `asyncio.Future` and Twisted's `Deferred` class when`tornado.platform.asyncio` and `tornado.platform.twisted` are imported.See the [`convert_yielded`](# "tornado.gen.convert_yielded") function to extend this mechanism.
Changed in version 3.2: Dict support added.
Changed in version 4.1: Support added for yielding `asyncio` Futures and Twisted Deferredsvia `singledispatch`.
### Decorators
`tornado.gen.``coroutine`(*func*, *replace_callback=True*)[[source]](#)
Decorator for asynchronous generators.
Any generator that yields objects from this module must be wrappedin either this decorator or [`engine`](# "tornado.gen.engine").
Coroutines may “return” by raising the special exception[`Return(value)`](# "tornado.gen.Return"). In Python 3.3+, it is also possible forthe function to simply use the `return value` statement (prior toPython 3.3 generators were not allowed to also return values).In all versions of Python a coroutine that simply wishes to exitearly may use the `return` statement without a value.
Functions with this decorator return a [`Future`](# "tornado.concurrent.Future"). Additionally,they may be called with a `callback` keyword argument, whichwill be invoked with the future's result when it resolves. If thecoroutine fails, the callback will not be run and an exceptionwill be raised into the surrounding [`StackContext`](# "tornado.stack_context.StackContext"). The`callback` argument is not visible inside the decoratedfunction; it is handled by the decorator itself.
From the caller's perspective, `@gen.coroutine` is similar tothe combination of `@return_future` and `@gen.engine`.
Warning
When exceptions occur inside a coroutine, the exceptioninformation will be stored in the [`Future`](# "tornado.concurrent.Future") object. You mustexamine the result of the [`Future`](# "tornado.concurrent.Future") object, or the exceptionmay go unnoticed by your code. This means yielding the functionif called from another coroutine, using something like[`IOLoop.run_sync`](# "tornado.ioloop.IOLoop.run_sync") for top-level calls, or passing the [`Future`](# "tornado.concurrent.Future")to [`IOLoop.add_future`](# "tornado.ioloop.IOLoop.add_future").
`tornado.gen.``engine`(*func*)[[source]](#)
Callback-oriented decorator for asynchronous generators.
This is an older interface; for new code that does not need to becompatible with versions of Tornado older than 3.0 the[`coroutine`](# "tornado.gen.coroutine") decorator is recommended instead.
This decorator is similar to [`coroutine`](# "tornado.gen.coroutine"), except it does notreturn a [`Future`](# "tornado.concurrent.Future") and the `callback` argument is not treatedspecially.
In most cases, functions decorated with [`engine`](# "tornado.gen.engine") should takea `callback` argument and invoke it with their result whenthey are finished. One notable exception is the[`RequestHandler`](# "tornado.web.RequestHandler")[HTTP verb methods](#),which use `self.finish()` in place of a callback argument.
### Utility functions
*exception *`tornado.gen.``Return`(*value=None*)[[source]](#)
Special exception to return a value from a [`coroutine`](# "tornado.gen.coroutine").
If this exception is raised, its value argument is used as theresult of the coroutine:
~~~
@gen.coroutine
def fetch_json(url):
response = yield AsyncHTTPClient().fetch(url)
raise gen.Return(json_decode(response.body))
~~~
In Python 3.3, this exception is no longer necessary: the `return`statement can be used directly to return a value (previously`yield` and `return` with a value could not be combined in thesame function).
By analogy with the return statement, the value argument is optional,but it is never necessary to `raise gen.Return()`. The `return`statement can be used with no arguments instead.
`tornado.gen.``with_timeout`(*timeout*, *future*, *io_loop=None*, *quiet_exceptions=()*)[[source]](#)
Wraps a [`Future`](# "tornado.concurrent.Future") in a timeout.
Raises [`TimeoutError`](# "tornado.gen.TimeoutError") if the input future does not complete before`timeout`, which may be specified in any form allowed by[`IOLoop.add_timeout`](# "tornado.ioloop.IOLoop.add_timeout") (i.e. a [`datetime.timedelta`](https://docs.python.org/3.4/library/datetime.html#datetime.timedelta "(in Python v3.4)") [https://docs.python.org/3.4/library/datetime.html#datetime.timedelta] or an absolute timerelative to [`IOLoop.time`](# "tornado.ioloop.IOLoop.time"))
If the wrapped [`Future`](# "tornado.concurrent.Future") fails after it has timed out, the exceptionwill be logged unless it is of a type contained in `quiet_exceptions`(which may be an exception type or a sequence of types).
Currently only supports Futures, not other [`YieldPoint`](# "tornado.gen.YieldPoint") classes.
New in version 4.0.
Changed in version 4.1: Added the `quiet_exceptions` argument and the logging of unhandledexceptions.
*exception *`tornado.gen.``TimeoutError`[[source]](#)
Exception raised by `with_timeout`.
`tornado.gen.``sleep`(*duration*)[[source]](#)
Return a [`Future`](# "tornado.concurrent.Future") that resolves after the given number of seconds.
When used with `yield` in a coroutine, this is a non-blockinganalogue to [`time.sleep`](https://docs.python.org/3.4/library/time.html#time.sleep "(in Python v3.4)") [https://docs.python.org/3.4/library/time.html#time.sleep] (which should not be used in coroutinesbecause it is blocking):
~~~
yield gen.sleep(0.5)
~~~
Note that calling this function on its own does nothing; you mustwait on the [`Future`](# "tornado.concurrent.Future") it returns (usually by yielding it).
New in version 4.1.
`tornado.gen.``moment`
A special object which may be yielded to allow the IOLoop to run forone iteration.
This is not needed in normal use but it can be helpful in long-runningcoroutines that are likely to yield Futures that are ready instantly.
Usage: `yield gen.moment`
New in version 4.0.
*class *`tornado.gen.``WaitIterator`(**args*, ***kwargs*)[[source]](#)
Provides an iterator to yield the results of futures as they finish.
Yielding a set of futures like this:
`results = yield [future1, future2]`
pauses the coroutine until both `future1` and `future2`return, and then restarts the coroutine with the results of bothfutures. If either future is an exception, the expression willraise that exception and all the results will be lost.
If you need to get the result of each future as soon as possible,or if you need the result of some futures even if others produceerrors, you can use `WaitIterator`:
~~~
wait_iterator = gen.WaitIterator(future1, future2)
while not wait_iterator.done():
try:
result = yield wait_iterator.next()
except Exception as e:
print("Error {} from {}".format(e, wait_iterator.current_future))
else:
print("Result {} received from {} at {}".format(
result, wait_iterator.current_future,
wait_iterator.current_index))
~~~
Because results are returned as soon as they are available theoutput from the iterator *will not be in the same order as theinput arguments*. If you need to know which future produced thecurrent result, you can use the attributes`WaitIterator.current_future`, or `WaitIterator.current_index`to get the index of the future from the input list. (if keywordarguments were used in the construction of the [`WaitIterator`](# "tornado.gen.WaitIterator"),`current_index` will use the corresponding keyword).
On Python 3.5, [`WaitIterator`](# "tornado.gen.WaitIterator") implements the async iteratorprotocol, so it can be used with the `async for` statement (notethat in this version the entire iteration is aborted if any valueraises an exception, while the previous example can continue pastindividual errors):
~~~
async for result in gen.WaitIterator(future1, future2):
print("Result {} received from {} at {}".format(
result, wait_iterator.current_future,
wait_iterator.current_index))
~~~
New in version 4.1.
Changed in version 4.3: Added `async for` support in Python 3.5.
`done`()[[source]](#)
Returns True if this iterator has no more results.
`next`()[[source]](#)
Returns a [`Future`](# "tornado.concurrent.Future") that will yield the next available result.
Note that this [`Future`](# "tornado.concurrent.Future") will not be the same object as any ofthe inputs.
`tornado.gen.``multi`(*children*, *quiet_exceptions=()*)[[source]](#)
Runs multiple asynchronous operations in parallel.
`children` may either be a list or a dict whose values areyieldable objects. `multi()` returns a new yieldableobject that resolves to a parallel structure containing theirresults. If `children` is a list, the result is a list ofresults in the same order; if it is a dict, the result is a dictwith the same keys.
That is, `results = yield multi(list_of_futures)` is equivalentto:
~~~
results = []
for future in list_of_futures:
results.append(yield future)
~~~
If any children raise exceptions, `multi()` will raise the firstone. All others will be logged, unless they are of typescontained in the `quiet_exceptions` argument.
If any of the inputs are [`YieldPoints`](# "tornado.gen.YieldPoint"), the returnedyieldable object is a [`YieldPoint`](# "tornado.gen.YieldPoint"). Otherwise, returns a [`Future`](# "tornado.concurrent.Future").This means that the result of [`multi`](# "tornado.gen.multi") can be used in a nativecoroutine if and only if all of its children can be.
In a `yield`-based coroutine, it is not normally necessary tocall this function directly, since the coroutine runner willdo it automatically when a list or dict is yielded. However,it is necessary in `await`-based coroutines, or to passthe `quiet_exceptions` argument.
This function is available under the names `multi()` and `Multi()`for historical reasons.
Changed in version 4.2: If multiple yieldables fail, any exceptions after the first(which is raised) will be logged. Added the `quiet_exceptions`argument to suppress this logging for selected exception types.
Changed in version 4.3: Replaced the class `Multi` and the function `multi_future`with a unified function `multi`. Added support for yieldablesother than [`YieldPoint`](# "tornado.gen.YieldPoint") and [`Future`](# "tornado.concurrent.Future").
`tornado.gen.``multi_future`(*children*, *quiet_exceptions=()*)[[source]](#)
Wait for multiple asynchronous futures in parallel.
This function is similar to [`multi`](# "tornado.gen.multi"), but does not support[`YieldPoints`](# "tornado.gen.YieldPoint").
New in version 4.0.
Changed in version 4.2: If multiple `Futures` fail, any exceptions after the first (which israised) will be logged. Added the `quiet_exceptions`argument to suppress this logging for selected exception types.
Deprecated since version 4.3: Use [`multi`](# "tornado.gen.multi") instead.
`tornado.gen.``Task`(*func*, **args*, ***kwargs*)[[source]](#)
Adapts a callback-based asynchronous function for use in coroutines.
Takes a function (and optional additional arguments) and runs it withthose arguments plus a `callback` keyword argument. The argument passedto the callback is returned as the result of the yield expression.
Changed in version 4.0: `gen.Task` is now a function that returns a [`Future`](# "tornado.concurrent.Future"), instead ofa subclass of [`YieldPoint`](# "tornado.gen.YieldPoint"). It still behaves the same way whenyielded.
*class *`tornado.gen.``Arguments`
The result of a [`Task`](# "tornado.gen.Task") or [`Wait`](# "tornado.gen.Wait") whose callback had more than oneargument (or keyword arguments).
The [`Arguments`](# "tornado.gen.Arguments") object is a [`collections.namedtuple`](https://docs.python.org/3.4/library/collections.html#collections.namedtuple "(in Python v3.4)") [https://docs.python.org/3.4/library/collections.html#collections.namedtuple] and can beused either as a tuple `(args, kwargs)` or an object with attributes`args` and `kwargs`.
`tornado.gen.``convert_yielded`(*yielded*)[[source]](#)
Convert a yielded object into a [`Future`](# "tornado.concurrent.Future").
The default implementation accepts lists, dictionaries, and Futures.
If the [`singledispatch`](https://docs.python.org/3.4/library/functools.html#functools.singledispatch "(in Python v3.4)") [https://docs.python.org/3.4/library/functools.html#functools.singledispatch] library is available, this functionmay be extended to support additional types. For example:
~~~
@convert_yielded.register(asyncio.Future)
def _(asyncio_future):
return tornado.platform.asyncio.to_tornado_future(asyncio_future)
~~~
New in version 4.1.
`tornado.gen.``maybe_future`(*x*)[[source]](#)
Converts `x` into a [`Future`](# "tornado.concurrent.Future").
If `x` is already a [`Future`](# "tornado.concurrent.Future"), it is simply returned; otherwiseit is wrapped in a new [`Future`](# "tornado.concurrent.Future"). This is suitable for use as`result = yield gen.maybe_future(f())` when you don't know whether`f()` returns a [`Future`](# "tornado.concurrent.Future") or not.
Deprecated since version 4.3: This function only handles `Futures`, not other yieldable objects.Instead of [`maybe_future`](# "tornado.gen.maybe_future"), check for the non-future result typesyou expect (often just `None`), and `yield` anything unknown.
### Legacy interface
Before support for [`Futures`](# "tornado.concurrent.Future") was introduced in Tornado 3.0,coroutines used subclasses of [`YieldPoint`](# "tornado.gen.YieldPoint") in their `yield` expressions.These classes are still supported but should generally not be usedexcept for compatibility with older interfaces. None of these classesare compatible with native (`await`-based) coroutines.
*class *`tornado.gen.``YieldPoint`[[source]](#)
Base class for objects that may be yielded from the generator.
Deprecated since version 4.0: Use [`Futures`](# "tornado.concurrent.Future") instead.
`start`(*runner*)[[source]](#)
Called by the runner after the generator has yielded.
No other methods will be called on this object before `start`.
`is_ready`()[[source]](#)
Called by the runner to determine whether to resume the generator.
Returns a boolean; may be called more than once.
`get_result`()[[source]](#)
Returns the value to use as the result of the yield expression.
This method will only be called once, and only after [`is_ready`](# "tornado.gen.YieldPoint.is_ready")has returned true.
*class *`tornado.gen.``Callback`(*key*)[[source]](#)
Returns a callable object that will allow a matching [`Wait`](# "tornado.gen.Wait") to proceed.
The key may be any value suitable for use as a dictionary key, and isused to match `Callbacks` to their corresponding `Waits`. The keymust be unique among outstanding callbacks within a single run of thegenerator function, but may be reused across different runs of the samefunction (so constants generally work fine).
The callback may be called with zero or one arguments; if an argumentis given it will be returned by [`Wait`](# "tornado.gen.Wait").
Deprecated since version 4.0: Use [`Futures`](# "tornado.concurrent.Future") instead.
*class *`tornado.gen.``Wait`(*key*)[[source]](#)
Returns the argument passed to the result of a previous [`Callback`](# "tornado.gen.Callback").
Deprecated since version 4.0: Use [`Futures`](# "tornado.concurrent.Future") instead.
*class *`tornado.gen.``WaitAll`(*keys*)[[source]](#)
Returns the results of multiple previous [`Callbacks`](# "tornado.gen.Callback").
The argument is a sequence of [`Callback`](# "tornado.gen.Callback") keys, and the result isa list of results in the same order.
[`WaitAll`](# "tornado.gen.WaitAll") is equivalent to yielding a list of [`Wait`](# "tornado.gen.Wait") objects.
Deprecated since version 4.0: Use [`Futures`](# "tornado.concurrent.Future") instead.
*class *`tornado.gen.``MultiYieldPoint`(*children*, *quiet_exceptions=()*)[[source]](#)
Runs multiple asynchronous operations in parallel.
This class is similar to [`multi`](# "tornado.gen.multi"), but it always creates a stackcontext even when no children require it. It is not compatible withnative coroutines.
Changed in version 4.2: If multiple `YieldPoints` fail, any exceptions after the first(which is raised) will be logged. Added the `quiet_exceptions`argument to suppress this logging for selected exception types.
Changed in version 4.3: Renamed from `Multi` to `MultiYieldPoint`. The name `Multi`remains as an alias for the equivalent [`multi`](# "tornado.gen.multi") function.
Deprecated since version 4.3: Use [`multi`](# "tornado.gen.multi") instead.
© Copyright 2009-2016, The Tornado Authors. Created using [Sphinx](http://sphinx-doc.org/) 1.3.5.
- User's guide
- Introduction
- Asynchronous and non-Blocking I/O
- Coroutines
- Queue example - a concurrent web spider
- Structure of a Tornado web application
- Templates and UI
- Authentication and security
- Running and deploying
- Web framework
- tornado.web — RequestHandler and Application classes
- tornado.template — Flexible output generation
- tornado.escape — Escaping and string manipulation
- tornado.locale — Internationalization support
- tornado.websocket — Bidirectional communication to the browser
- HTTP servers and clients
- tornado.httpserver — Non-blocking HTTP server
- tornado.httpclient — Asynchronous HTTP client
- tornado.httputil — Manipulate HTTP headers and URLs
- tornado.http1connection – HTTP/1.x client/server implementation
- Asynchronous networking
- tornado.ioloop — Main event loop
- tornado.iostream — Convenient wrappers for non-blocking sockets
- tornado.netutil — Miscellaneous network utilities
- tornado.tcpclient — IOStream connection factory
- tornado.tcpserver — Basic IOStream-based TCP server
- Coroutines and concurrency
- tornado.gen — Simplify asynchronous code
- tornado.concurrent — Work with threads and futures
- tornado.locks – Synchronization primitives
- tornado.queues – Queues for coroutines
- tornado.process — Utilities for multiple processes
- Integration with other services
- tornado.auth — Third-party login with OpenID and OAuth
- tornado.wsgi — Interoperability with other Python frameworks and servers
- tornado.platform.asyncio — Bridge between asyncio and Tornado
- tornado.platform.caresresolver — Asynchronous DNS Resolver using C-Ares
- tornado.platform.twisted — Bridges between Twisted and Tornado
- Utilities
- tornado.autoreload — Automatically detect code changes in development
- tornado.log — Logging support
- tornado.options — Command-line parsing
- tornado.stack_context — Exception handling across asynchronous callbacks
- tornado.testing — Unit testing support for asynchronous code
- tornado.util — General-purpose utilities
- Frequently Asked Questions
- Release notes
- What's new in Tornado 4.3
- What's new in Tornado 4.2.1
- What's new in Tornado 4.2
- What's new in Tornado 4.1
- What's new in Tornado 4.0.2
- What's new in Tornado 4.0.1
- What's new in Tornado 4.0
- What's new in Tornado 3.2.2
- What's new in Tornado 3.2.1
- What's new in Tornado 3.2
- What's new in Tornado 3.1.1
- What's new in Tornado 3.1
- What's new in Tornado 3.0.2
- What's new in Tornado 3.0.1
- What's new in Tornado 3.0
- What's new in Tornado 2.4.1
- What's new in Tornado 2.4
- What's new in Tornado 2.3
- What's new in Tornado 2.2.1
- What's new in Tornado 2.2
- What's new in Tornado 2.1.1
- What's new in Tornado 2.1
- What's new in Tornado 2.0
- What's new in Tornado 1.2.1
- What's new in Tornado 1.2
- What's new in Tornado 1.1.1
- What's new in Tornado 1.1
- What's new in Tornado 1.0.1
- What's new in Tornado 1.0