decorators tutorials
Scott David Daniels
Scott.Daniels at Acm.Org
Mon Mar 23 18:26:04 EDT 2009
Josiah Carlson wrote:
> ... I try to limit my use of decorators whenever possible, both because I
> still have to support Python 2.3 (which doesn't support the syntax), and
> because I find that they obfuscate what the code is doing more often
> than not. I will admit that they are useful as a metaprogramming
> technique. Just be careful.
I find them very useful in debugging (for example writing a decorator
'traced'), and have also used them to simplify code that puts a lot
of functions into a dictionary. In the latter case, the function can
be returned unadorned, or can be stored, and only the locater for the
function returned:
function_table = []
def enumerated(function):
function_table.append(function)
return len(function_table) - 1
@enumerated
def triple(a, b, c):
blah, blah, blah
@enumerated
def double(a, b):
blah, blah, blah
@enumerated
def another(a, b, c):
blah, blah, blah
After all of that, the identifiers triple, double, and another refer
to 0, 1, and 2 respectively, and you can call functions with the
following structure:
function_table[double]('pi', 3.14)
This can be very useful for certain kinds of table-driven code (where
you may want to be able to efficiently store lists of functions to call
in data files).
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list