Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 643
Duke Dougal Avatar asked Aug 21 '12 00:08

Duke Dougal


People also ask

What is the Python decorator give an example?

You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.

Why would you use a decorator Python?

Also, decorators are useful for Memoizing - that is caching a slow-to-compute result of a function. The decorator can return a function that checks the inputs, and if they have already been presented, return a cached result. Note that Python has a built-in decorator, functools.

What is decorator in Python with example interview questions?

When we mention the word "decorator", what enters your mind? Well, likely something that adds beauty to an existing object. An example is when we hang a picture frame to a wall to enhance the room. Decorators in Python add some feature or functionality to an existing function without altering it.


1 Answers

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.

like image 126
Blender Avatar answered Sep 20 '22 15:09

Blender