Python – Understanding Decorators in Python

python

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

Best Answer

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.

Related Topic