473,386 Members | 2,050 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

What are decorators?

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 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

Jul 18 '05 #1
2 1418
gohaku wrote:
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?


In Python, at least, they seem to be syntactic sugar for the following,
as the PEP clearly shows:

def func():
pass

func = decorator(func)
That is equivalent to this with the new proposed syntax (and this is
no doubt out of date because I wrote it more than two minutes ago):

@decorator
def func():
pass
In other words, they are simply a function that takes a function
and does something to or with it, returning a new function, or
perhaps the old one, when it's done.

The original use cases seem to have been staticmethod and classmethod.
Python doesn't have special syntax for defining these, as for
example Java does, so the idiom shown first above was developed,
along with a staticmethod() or classmethod() "decorator" function
which would modify the original non-static method so that it was
now a static method.

The folks using this decided they didn't like the fact that the
modification came *after* the function definition, since it could
be hard to notice it, and probably they didn't really like the
feel of the whole thing, since it's sort of hackish and inelegant.

If you don't need staticmethod (and the answer to the question
"do I need staticmethod?" is "no"), then you don't really need
decorators. :-)

-Peter
Jul 18 '05 #2


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.

Jul 18 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Michael Sparks | last post by:
Anyway... At Europython Guido discussed with everyone the outstanding issue with decorators and there was a clear majority in favour of having them, which was good. From where I was sitting it...
4
by: Doug Holton | last post by:
First let me say please see the wiki page about python decorators if you haven't already: http://www.python.org/cgi-bin/moinmoin/PythonDecorators I propose (and others have) that built-in...
8
by: Michele Simionato | last post by:
Decorators can generate endless debate about syntax, but can also be put to better use ;) Actually I was waiting for decorators to play a few tricks that were syntactically too ugly to be even...
12
by: Colin J. Williams | last post by:
Christopher T. King suggested that "we're trying to kill too many birds with one stone". ...
65
by: Miklós | last post by:
Ok, seems like we have @decorators. It's a nice tribute to Intercal. But I'd prefer #decorators. We have metaclasses for pleasure brain-melting. We have generators, new-style classes and...
37
by: Bengt Richter | last post by:
ISTM that @limited_expression_producing_function @another def func(): pass is syntactic sugar for creating a hidden list of functions. (Using '|' in place of '@' doesn't change the picture...
2
by: Guido van Rossum | last post by:
Robert and Python-dev, I've read the J2 proposal up and down several times, pondered all the issues, and slept on it for a night, and I still don't like it enough to accept it. The only reason...
2
by: Andrew West | last post by:
Probably a bit of weird question. I realise decorators shouldn't be executed until the function they are defined with are called, but is there anyway for me to find all the decorates declared in a...
0
by: Scott SA | last post by:
Hi, I've been trying to wrap my head around decorators and in my trails found avery recent article on Linux Mag's website. I didn't see a post here regarding this article and feel it is worth...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.