Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am just learning python, and I am currently playing with Tornado framework. I see this class:

class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    @tornado.web.asynchronous
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()

I am having trouble grasping what the decorator does there (@tornado.web.asynchronous). Does it overwrite that function?

You can see the full source at https://github.com/facebook/tornado/blob/master/demos/chat/chatdemo.py

share|improve this question

2 Answers 2

up vote 4 down vote accepted

Yes, it probably does, but it proprably retains a reference to the original get(self) definition.

Python decorators are nothing more than a callable themselves (a function, or a class instance with a __call__ method). Whatever that callable returns is used as the definition for the decorated function instead.

If I define a simple no-op decorator like this, that means that I replace the original with.... the original:

def noopDecorator(func):
    return func

The @ symbol used for decorators is syntactic sugar, you could also write it as:

class AuthHandler(BaseHandler, tornado.auth.GoogleMixin):
    def get(self):
        if self.get_argument("openid.mode", None):
            self.get_authenticated_user(self.async_callback(self._on_auth))
            return
        self.authenticate_redirect()
    get = tornado.web.asynchronous(get)

In the case of the tornado asynchronous decorator, the decorator probably returns a deferred handler, to handle the decorated function asynchronously, keeping you, the programmer of a tornado-based application, from having to remember the intricacies of how to do that, time and again. In short, it let's you focus on the details of your application instead.

share|improve this answer
    
That alternate syntax makes sense to me to see how decorators work, thank you. I also found this answer later on stack overflow and it helped also: stackoverflow.com/questions/739654/… –  Clint Jul 26 '12 at 8:00

You can see the documentation for @tornado.web.asynchronous can be found here http://www.tornadoweb.org/documentation/web.html#tornado.web.asynchronous.

But basically it means that the method will be run asynchronously if possible.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.