10

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?
Rudziankoŭ
  • 10,681
  • 20
  • 92
  • 192

2 Answers2

5
Tms91
  • 3,456
  • 6
  • 40
  • 74
Paul
  • 315
  • 1
  • 9
  • Thanks for your answer. I found out documentation for `gen.Return`. """Special exception to return a value from a `coroutine`. If this exception is raised, its value argument is used as the result of the coroutine:: `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 the same function). """ – Rudziankoŭ Jun 03 '16 at 13:00
4

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.
Tms91
  • 3,456
  • 6
  • 40
  • 74
james.bondu
  • 1,092
  • 2
  • 18
  • 27