[Tutor] decorators (the "at" sign)?

James Mills prologic at shortcircuit.net.au
Tue Oct 26 05:08:32 CEST 2010


On Tue, Oct 26, 2010 at 12:46 PM, Alex Hall <mehgcap at gmail.com> wrote:
>  @set_index
>  def get_url(self, index=None):
>  return self.storage[index]['Url']

Decorators in python are used (almost as convenience) to wrap
functions/methods for various purposes.
It might be to do some logging before and after the actual function is
called, or setup static methods, etc.

The "@" symbol was chosen for this, and in the above example the
following is happening:

The method get_url(...) is being decorated (as opposed to being
wrapped) with the set_index(...) function.
(Without knowing too much more about the code you're looking at...)
set_index(...) would be doing something
with the get_url(...) method then returning it.

The best example of this is the following from PEP 318 (1):

def onexit(f):
    import atexit
    atexit.register(f)
    return f

@onexit
def func():
    ...

This has a similar form to the code you're studying and registers func
with atexit hooks so that when
the application terminates, func(...) gets called.

Hope this helps,

cheers
James

1. http://www.python.org/dev/peps/pep-0318/

-- 
-- James Mills
--
-- "Problems are solved by method"


More information about the Tutor mailing list