[Baypiggies] Examples of Handy Decorators
simeonf at gmail.com
Sun Jul 18 21:21:35 CEST 2010
On Sun, Jul 18, 2010 at 9:46 AM, Glen Jarvis <glen at glenjarvis.com> wrote:
> The focus of my very quick presentation will be on the *why to use* (not how
> to write) -- which seems to be the biggest stumbling block for those just
> learning. I think this is mitigated by giving concrete small-but-not-toy
As far as the "why" goes - I think the history makes clear some of the
advantages of decorator syntax. I've heard that decorators in python
started with the classmethod/staticmethod builtins. You start out with
the syntax that shows what's going on:
myfunc = staticmethod(myfunc)
This makes clear what is going on - the method myfunc is modified in
some way by the staticmethod builtin.
But it seems kind of ugly if you scan lots of code using this idiom -
especially with long functions you don't know that the function is
somehow "special" until you get to the bottom.
Using the @decorator syntax makes the decorated functions stand out.
And this comes into play with the most common examples of decorators
I've heard. Your example is a good one, If you have a Django views
file with a dozen view functions, some of which require authentication
and some of which don't, using decorators makes it easy to scan
quickly - I've found bugs due to just noticing the missing @ above a
function. Static/Class methods fit this pattern. And other typical
examples (logging, synchronization) fit this pattern as well - you've
got a bunch of functions and @decorator syntax makes explicit visually
which ones acquire a lock, etc.
> Once a person gets the *why*, I think its easier to get to the *how*
> (although there can be some new concepts in there too)...
> Let the brainstorming/ideas roll :) pretty please :)
> Whatever you can do or imagine, begin it;
> boldness has beauty, magic, and power in it.
> -- Goethe
> Baypiggies mailing list
> Baypiggies at python.org
> To change your subscription options or unsubscribe:
More information about the Baypiggies