Search code examples
pythonpython-3.xfunctiondecoratorpython-decorators

Python decorator? - can someone please explain this?


Apologies this is a very broad question.

The code below is a fragment of something found on the web. The key thing I am interested in is the line beginning @protected - I am wondering what this does and how it does it? It appears to be checking that a valid user is logged in prior to executing the do_upload_ajax function. That looks like a really effective way to do user authentication. I don't understand the mechanics of this @ function though - can someone steer me in the right direction to explain how this would be implemented in the real world? Python 3 answers please. thanks.

@bottle.route('/ajaxupload', method='POST')
@protected(check_valid_user) 
def do_upload_ajax():
    data = bottle.request.files.get('data')
    if data.file:
        size = 0

Solution

  • Take a good look at this enormous answer/novel. It's one of the best explanations I've come across.

    The shortest explanation that I can give is that decorators wrap your function in another function that returns a function.

    This code, for example:

    @decorate
    def foo(a):
      print a
    

    would be equivalent to this code if you remove the decorator syntax:

    def bar(a):
      print a
    
    foo = decorate(bar)
    

    Decorators sometimes take parameters, which are passed to the dynamically generated functions to alter their output.

    Another term you should read up on is closure, as that is the concept that allows decorators to work.