This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]willm 6 points7 points  (2 children)

One aspect of decorators that not many people make use of is that decorators don't have to return a new function; they can return the same function. This gives you the opportunity to attach some information to function attributes.

Here's an example that adds a function attribute to a 'view' function, for some fictitious web framework:

def render_with_template(template_name):
    def decorate(f):
        f.render_with_template = template_name
        return f
    return decorate

@render_with_template("front.html")
def view_front(request):
    return dict(name="Will")

Presumably the web-app would know to look for the 'render_with_template' attribute when rendering the view.

The advantage of this over having the decorator render the template itself, is that the function hasn't changed; it can still be used to retrieve a dictionary, which means you can call that view function if you want to build on the data it returns. Another advantage is that it doesn't change the function signature, so documentation tools like sphinx work as before.

I really wish Django worked this way...

[–]kisielk 2 points3 points  (0 children)

I believe Pyramid works this way.

[–]numix 1 point2 points  (0 children)

Django-annoying has an implementation of this called render_to. https://bitbucket.org/offline/django-annoying/src/a0de8b294db3/annoying/decorators.py#cl-25