473,320 Members | 1,914 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,320 software developers and data experts.

decorators ?

km
Hi all,
was going thru the new features introduced into python2.4 version.
i was stuck with 'decorators' - can someone explain me the need of such a thing called decorators ?
tia
KM
Jul 18 '05 #1
13 2327
"km" <km@mrna.tn.nic.in> wrote in message
news:ma**************************************@pyth on.org...
Hi all,
was going thru the new features introduced into python2.4 version.
i was stuck with 'decorators' - can someone explain me the need of such a thing called decorators ? tia
KM


Here are some example on the Python Wiki:
http://www.python.org/moin/PythonDecoratorLibrary

I think memoize is my favorite so far.

I'm not sure if the example behavior is all that clear. For a given set of
arguments, the Memoize class keeps a dictionary of input arg values and
return values. In subsequent calls, sets of args are looked up in the
dictionary of previous calls - if the arg list is found, then the function
is bypassed, and the cached return value is returned immediately. This can
greatly speed up calls to functions that are very time-consuming, or
recursive. This is why the Wiki page lists factorial() and fibonacci()
examples. Of course, Memoize assumes that the return value is purely a
function of the input args, and not subject to any external state.

Of course, one could readily implement this behavior within the target
functions. The beauty of the decorator is that this optimization is done
*completely* outside the function itself, so the function remains fairly
pure at the application level, and does not get cluttered with variables
like "resultsCache" and so on. Also, in the interests of maximizing reuse
and avoiding the bug-proneness of cut-and-paste, isolating Memoize into a
reusable decorator helps avoid introducing bugs (vs. hard-coding this
optimization into successive functions - did you remember to initialize the
dictionary?), and leverages any optimizations or bug-fixes.

(I focused on Memoize, but these comments apply to any of the decorators on
this wiki page.)

-- Paul
Jul 18 '05 #2
Some more decorator examples.

How to create abstract methods using an @absractmethod decorator:
http://www.brpreiss.com/books/opus7/html/page117.html

Generics, property getters and setters. I don't know what these
decorators are supposed to do:
http://www.cis.upenn.edu/~edloper/pydecorators.html -

And according to this,
http://www.prothon.org/pipermail/pro...st/003173.html,
one use of decorators is to put a functions docstring before the def
f(): line like this:

@doc("""blabla does something.""")
def blabla():

Here is one decorator for optimizing:
http://aspn.activestate.com/ASPN/Coo.../Recipe/277940

I think the essence of decorators is that it makes it possible to do
in Python what you in other languages do with method qualifiers. This
declaration in Java

public synchronized static void doStuff()

would you write in Python as

@public
@synchronized
@staticmethod
def doStuff():

I haven't seen an example of a @synchronized decorator, but I assume
it is possible. Hopefully, it is possible to create a @private
decorator which throws some kind of exception when a private method is
accessed from outside the class. If that is possible, then it would
also be nice to have a @public decorator which doesn't do anything. As
far as I know, only two decorators are included in the standard
library in Python 2.4, @staticmethod and @classmethod. That is a
little unfortunate, because many more "obvious ones" could have been
included. The devs are probably planning to correct that in the coming
versions.
That is all I know about decorators. Or rather THINK I know from
reading stuff on the internet. Please don't flame me if I'm wrong. :)

--
mvh Björn
Jul 18 '05 #3
BJörn Lindqvist <bj*****@gmail.com> writes:
I think the essence of decorators is that it makes it possible to do
in Python what you in other languages do with method qualifiers.


I find it fascinating that the addition of a bit of syntax sugar gives
the perception that a whole range of new and previously unthinkable
possibilities have opened themselves before us.

@X
def Y...
...
is merely syntax sugar (or syntax ammonia, for some) for
def Y...
...
Y = X(Y)

Anything you can do with decorators, you could do before (with the
exception of rebinding the __name__ of functions).

And yet, that bit of syntax sugar really _does_ make a big difference
to the lengths that people are prepared to take the possibilities that
the underlying feature affords them.
Jul 18 '05 #4

Jacek> Anything you can do with decorators, you could do before (with
Jacek> the exception of rebinding the __name__ of functions).

And while that feature was added because we realized it would be nice if the
decorated function could have the same name as the original function, it
seems like that change could stand on its own merits.

Skip
Jul 18 '05 #5
Skip Montanaro <sk**@pobox.com> writes:
Jacek> Anything you can do with decorators, you could do before (with
Jacek> the exception of rebinding the __name__ of functions).

And while that feature was added because we realized it would be nice if the
decorated function could have the same name as the original function, it
seems like that change could stand on its own merits.


Indeed. I'd been meaning to do it for at least a year...

Cheers,
mwh

--
Never meddle in the affairs of NT. It is slow to boot and quick to
crash. -- Stephen Harris
-- http://home.xnet.com/~raven/Sysadmin/ASR.Quotes.html
Jul 18 '05 #6

Jacek Generowicz <ja**************@cern.ch> wrote:

BJörn Lindqvist <bj*****@gmail.com> writes:
I think the essence of decorators is that it makes it possible to do
in Python what you in other languages do with method qualifiers.


I find it fascinating that the addition of a bit of syntax sugar gives
the perception that a whole range of new and previously unthinkable
possibilities have opened themselves before us.

@X
def Y...
...


is merely syntax sugar (or syntax ammonia, for some) for


def Y...
...
Y = X(Y)

Anything you can do with decorators, you could do before (with the
exception of rebinding the __name__ of functions).

And yet, that bit of syntax sugar really _does_ make a big difference
to the lengths that people are prepared to take the possibilities that
the underlying feature affords them.

Technically, everything can be performed in assembly. The point of
syntactic sugar (or ammonia) is to make things less painful. While
everything was possible before, adding the decorators /after/ defining
the function hid the decorators, and was susceptible to mistyping.

I previously posted about Philip Eby's use of decorators in PyObjC. In
his case, it saved him from typing 40-character function names 3
times.

- Josiah

Jul 18 '05 #7

Jacek Generowicz <ja**************@cern.ch> wrote:

BJörn Lindqvist <bj*****@gmail.com> writes:
I think the essence of decorators is that it makes it possible to do
in Python what you in other languages do with method qualifiers.


I find it fascinating that the addition of a bit of syntax sugar gives
the perception that a whole range of new and previously unthinkable
possibilities have opened themselves before us.

@X
def Y...
...


is merely syntax sugar (or syntax ammonia, for some) for


def Y...
...
Y = X(Y)

Anything you can do with decorators, you could do before (with the
exception of rebinding the __name__ of functions).

And yet, that bit of syntax sugar really _does_ make a big difference
to the lengths that people are prepared to take the possibilities that
the underlying feature affords them.

Technically, everything can be performed in assembly. The point of
syntactic sugar (or ammonia) is to make things less painful. While
everything was possible before, adding the decorators /after/ defining
the function hid the decorators, and was susceptible to mistyping.

I previously posted about Philip Eby's use of decorators in PyObjC. In
his case, it saved him from typing 40-character function names 3
times.

- Josiah

Jul 18 '05 #8
On Tue, 30 Nov 2004 19:38:46 GMT, "Paul McGuire"
<pt***@austin.rr._bogus_.com> wrote:
"km" <km@mrna.tn.nic.in> wrote in message
news:ma**************************************@pyt hon.org...
Hi all,
was going thru the new features introduced into python2.4 version.
i was stuck with 'decorators' - can someone explain me the need of such a

thing called decorators ?
tia
KM


Here are some example on the Python Wiki:
http://www.python.org/moin/PythonDecoratorLibrary

I think memoize is my favorite so far.


Memoize is certainly a readily approachable example.

But the factorial example on the wiki has a defect. It incorrectly
calculates factorial(0) as 0, when it should be 1. I don't know how
to edit the "inline" code in the wiki, but if someone out there knows
how, consider changing:

if n < 2:
return n

to:

if n < 2:
return 1

Have a nice day!
--dang
Jul 18 '05 #9

"Daniel 'Dang' Griffith" <go*****@lazytwinacres.net> wrote in message
news:1102458244.004fc0dc548f5536ec77f769e501ff1e@t eranews...
But the factorial example on the wiki has a defect. It incorrectly
calculates factorial(0) as 0, when it should be 1.


This is a matter of definition, and definitions apparently differ. fact(0)
== 0 is a backward projection from the definition f(1) = f(2) = 1 in
1-based systems, which is the context for the rabbit problem in which the
first year is year 1, not year 0. Disagreement is not defect.

Terry J. Reedy

Jul 18 '05 #10
[Daniel 'Dang' Griffith]
But the factorial example on the wiki has a defect. It incorrectly
calculates factorial(0) as 0, when it should be 1.

[Terry Reedy] This is a matter of definition, and definitions apparently differ.
fact(0) == 0 is a backward projection from the definition f(1) = f(2)
= 1 in 1-based systems, which is the context for the rabbit
problem in which the first year is year 1, not year 0.
Disagreement is not defect.


Terry, since you're talking about "the rabbit problem", are you sure
you're talking about the factorial example? It sounds like you're
talking about the Fibonacci example. I agree with Daniel about the
factorial function: there's no disagreement about 0!=1, 1!=1, 2!=2,
3!=6, 4!=24, ..., that I've ever seen. The first two terms in a
Fibonacci sequence are indeed arbitrary, though.
Jul 18 '05 #11
Terry Reedy wrote:

"Daniel 'Dang' Griffith" <go*****@lazytwinacres.net> wrote in message
news:1102458244.004fc0dc548f5536ec77f769e501ff1e@t eranews...
But the factorial example on the wiki has a defect. It incorrectly
calculates factorial(0) as 0, when it should be 1.


This is a matter of definition, and definitions apparently differ. fact(0)
== 0 is a backward projection from the definition f(1) = f(2) = 1 in
1-based systems, which is the context for the rabbit problem in which the
first year is year 1, not year 0. Disagreement is not defect.


No, fact(0)==1 simply because any proper definition of a factorial has to match
up with the gamma function (offset by one) at all non-negative integers. So
there's no room for any ambiguity here.

Regards,

f

Jul 18 '05 #12
Fernando Perez wrote:
No, fact(0)==1 simply because any proper definition of a factorial has to
match
up with the gamma function (offset by one) at all non-negative integers. So
there's no room for any ambiguity here.


I should have added a link to the ever-useful mathworld:

http://mathworld.wolfram.com/Factorial.html

This has as much detail about n! and Gamma(z) as you'll ever want to know :)

Cheers,

f

Jul 18 '05 #13

"Tim Peters" <ti********@gmail.com> wrote in message
news:1f************************@mail.gmail.com...
Terry, since you're talking about "the rabbit problem", are you sure
you're talking about the factorial example? It sounds like you're
talking about the Fibonacci example.


Of course. 0! is 1 multiplied by nothing (not 0) which is 1, just as n**0
is 1 multiplied by n 0 times and hence 1.

TJR

Jul 18 '05 #14

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...
17
by: daishi | last post by:
For what it's worth: As far as I know, the proposed @decorator syntax will be the first time that two logical lines of python with the same indentation will not be independent of one another....
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...
4
by: RebelGeekz | last post by:
Just my humble opinion: def bar(low,high): meta: accepts(int,int) returns(float) #more code Use a metadata section, no need to introduce new messy symbols, or mangling our beloved visual...
11
by: Arien Malec | last post by:
I've been following the decorator debate with some interest, and it's taken me a reasonably long time to understand what is meant by a decorator. One of the issues is that the Decorator pattern is...
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...
0
by: Anthony Baxter | last post by:
To go along with the 2.4a3 release, here's an updated version of the decorator PEP. It describes the state of decorators as they are in 2.4a3. PEP: 318 Title: Decorators for Functions and...
11
by: Helmut Jarausch | last post by:
Hi, are decorators more than just syntactic sugar in python 2.x and what about python 3k ? How can I find out the predefined decorators? Many thanks for your help, Helmut Jarausch
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: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

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.