Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding of @gen.coroutine annotation

Tags:

python

tornado

I know that my question looks to broad, but I hope the answer on this question will give me correct direction what to read on. I am new to Tornado framework, basically I am new to Python. I am looking into this project: Could you please explain me a few lines of code:

@gen.coroutine
def get_me(self):
    raise gen.Return((yield self._api.get_me()))
  • What @gen.coroutine annotation is for?
  • raise keyword is used for exceptions, isn't it? Why we use it here?
  • Why we return everything in form of generator. Is the concept of Tornado framework to use generators. What is the reason?
like image 213
Rudziankoŭ Avatar asked Jun 03 '16 11:06

Rudziankoŭ


People also ask

What is gen coroutine?

Coroutines provide an easier way to work in an asynchronous environment than chaining callbacks. Code using coroutines is technically asynchronous, but it is written as a single generator instead of a collection of separate functions.

How do you create a coroutine function in Python?

In Python, coroutines are similar to generators but with few extra methods and slight changes in how we use yield statements. Generators produce data for iteration while coroutines can also consume data. whatever value we send to coroutine is captured and returned by (yield) expression.


2 Answers

  • @gen is a decorator, it will modify the function below it at definition.
  • It uses raise to return values and will catch it with except gen.Return (I find it ugly but it works).
  • Generators are a convinient way to avoid memory usage and allow lazy programing, always try to return a generator over an iterator.
like image 155
Paul Avatar answered Sep 28 '22 09:09

Paul


Following the Tornado documentation, I found that the general way to ensure async behavior is by the use of event loop and callback functions.
But using callbacks is syntactically difficult and kind of confusing.
So the developers of tornado came up with the use of decorators(just like flask,cherrypy etc).

  • When you follow the source code of Tornado, you will see gen.py module under which they define the coroutine decorator. It's really an elegant way to ensure concurrency in Tornado.
  • The raise is to handle exception. I find it quite easy as it simply returns except gen.Return.
  • Tornado use generators simply it's easy to use.
like image 20
james.bondu Avatar answered Sep 28 '22 09:09

james.bondu