Decorators and how they relate to Python - A little insight please!

johnzenger at gmail.com johnzenger at gmail.com
Thu Oct 19 17:12:29 EDT 2006


When you want to repeatedly apply a certain ALGORITHM to arbitrary sets
of DATA, you write a FUNCTION.

When you want to add a certain BEHAVIOR to arbitrary sets of FUNCTIONS,
you write a DECORATOR.

An excellent use of decorators is in Django, the web programming
framework.  Django keeps track of usernames and passwords for you.
Occasionally, there are some things on your web site that you only want
to only let people who are logged in do (like, say, leave a comment on
your blog).  Instead of making you begin every such function with "if
user_is_logged in:" or some similar abomination, Django lets you just
put a @require_login decorator before that function.  Pretty spiffy.


Jerry wrote:
> I have just started to do some semi-serious programming (not one-off
> specialized scripts) and am loving Python.  I just seem to get most of
> the concepts, the structure, and the classes (something I struggled
> with before in other languages).  I've seen many concepts on the web
> (i.e. stacks, queues, linked lists) and can usually understand them
> pretty well (event if I don't always know when to use them).  Now I've
> come accross decorators and even though I've read the PEP and a little
> in the documentation, I just don't get what they are or what problem
> they are trying to solve.  Can anyone please point me to a general
> discussion of decorators (preferrably explained with Python)?
> 
> Thanks,
> Jerry




More information about the Python-list mailing list