What are decorators?
Colin J. Williams
cjw at sympatico.ca
Mon Aug 9 15:57:59 EDT 2004
gohaku wrote:
> Hi everyone,
> The discussion on Python Decorators and "@" has piqued my interest on this
> "feature?" in programming languages such as Python and Java.
> can anybody what is the point in using Decorators?
>
The term decorator is a bit misleading. It does not decorate or adorn a
function, class or method declaration, the declaration is transformed.
There are cases where one might wish to change the behaviour of a
function to, for example ensure that the arguments being passed in
are of a certain class or that the object returned has given type.
> The examples I have seen written in Python of this "Not Yet Implemented"
> feature
> are confusing to say the least and perplexes me as to its usefulness.
>
> Thanks in advance.
> -gohaku
>
In a posting yerterday, Dan bishop wrote:
>
> If I understand correctly, they'd be useful for anything where you'd
> now use the syntax
>
> function = decorator(function)
>
> In addition to @staticmethod, you could have decorators for
>
> (1) Memoization. Makes repeated function evaluation more efficient
> without having to rewrite the function.
>
> class memoize(object):
> def __init__(self, func):
> self.__func = func
> self.__results = {}
> def __call__(self, *args):
> if args not in self.__results:
> self.__results[args] = self.__func(*args)
> return self.__results[args]
>
> def fibonacci(n):
> @memoize
> if n in (0, 1):
> return n
> return fibonacci(n - 1) + fibonacci(n - 2)
>
> (2) Debugging uses, like:
>
> class printreturns(object):
> "Behaves like f but prints its return values."
> def __init__(self, f):
> self.__f = f
> def __call__(self, *args):
> result = self.__f(*args)
> if debug:
> print 'f%r = %r' % (args, result)
> return
> def somefunc(x, y):
> @printreturns
> ...
I found it helpful, I hope that you do.
Colin W.
More information about the Python-list
mailing list