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

What are decorated functions?

I'm just reading the python language reference and came around
the term "decorated functions", but I have no idea, for what
they could be used.

Any reply gracefully accepted.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Aug 22 '06 #1
4 1967
PEP 318 provides some great examples:
http://www.python.org/dev/peps/pep-0318/

For more information no the decorator pattern in general:
http://en.wikipedia.org/wiki/Decorator_pattern

How one actually makes use of decorators beyond the above is an
exercise of imagination.

Wolfgang Draxinger wrote:
I'm just reading the python language reference and came around
the term "decorated functions", but I have no idea, for what
they could be used.

Any reply gracefully accepted.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Aug 22 '06 #2
Daniel O'Brien wrote:
How one actually makes use of decorators beyond the above is an
exercise of imagination.
Now it rings a bell, thx.

Wolfgang Draxinger
--
E-Mail address works, Jabber: he******@jabber.org, ICQ: 134682867
GPG key FP: 2FC8 319E C7D7 1ADC 0408 65C6 05F5 A645 1FD3 BD3E
Aug 22 '06 #3
At Tuesday 22/8/2006 17:19, Wolfgang Draxinger wrote:
>I'm just reading the python language reference and came around
the term "decorated functions", but I have no idea, for what
they could be used.
A decorator takes a function/method/callable, "decorates" (modifies)
it in a certain way, and returns it.
@classmethod and @staticmethod are examples: they take a (normal)
method, and transform it into another thing.
You can write your own decorators. An example similar to one
discussed on this list a few days ago: suppose you have a pure
function taking a long time to compute; you could save the results in
a dictionary using the arguments as key, and retrieve them later when
a call is made exactly with the same arguments. This is a known
pattern ("memoize").

def memoized(function):
function.cache={}
def f(*args):
try: return function.cache[args]
except KeyError:
result = function.cache[args] = function(*args)
return result
return f

@memoized
def fibo(n):
time.sleep(2) # a sloooooow function
if n<2: return 1
return fibo(n-1)+fibo(n-2)

The original function is fibo() - it works OK but assume it's slow.
So you "decorate" it with @memoized to improve performance.
(This is just an example, of course - I'm not saying memoizing is the
right thing to do here, nor this is the best way to do it... just to
demonstrate what a decorator could be used for)

Gabriel Genellina
Softlab SRL

__________________________________________________
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
¡Probalo ya!
http://www.yahoo.com.ar/respuestas

Aug 23 '06 #4
Gabriel Genellina wrote:
At Tuesday 22/8/2006 17:19, Wolfgang Draxinger wrote:
>I'm just reading the python language reference and came around
the term "decorated functions", but I have no idea, for what
they could be used.

A decorator takes a function/method/callable, "decorates" (modifies)
it in a certain way, and returns it.
It's important to note here that decorators, using the @decorate syntax[1],
*can only decorate methods and functions*. That is, they must be followed
by either another @decorator or a "def" statement. Anything else will
result in a SyntaxError. For example:
>>def test(callable): return callable
....
>>@test
.... def foo(): pass
....
>>@test
.... @test
.... @test
.... def foo(): pass
....
>>@test
.... class bar:
File "<stdin>", line 2
class bar:
^
SyntaxError: invalid syntax
>>@test
.... file
File "<stdin>", line 2
file
^
SyntaxError: invalid syntax
>>>
So you can't decorate classes (the original PEP proposed it, but it was
dropped - see the discussion about this on python-dev[2]). You *can*
decorate a class' __init__ method, but that's not quite the same as eg.
implementing @singleton (mind you, we already have a bazillion ways to
implement the singleton pattern, so I don't think we're poorer for this
limitation <wink>)
Richard

[1] of course, you can "anything = decorate(anything)"
[2] http://mail.python.org/pipermail/pyt...ch/052369.html
Aug 23 '06 #5

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

Similar topics

3
by: Ron_Adam | last post by:
Ok... it's works! :) So what do you think? Look at the last stacked example, it process the preprocess's first in forward order, then does the postprocess's in reverse order. Which might be...
0
by: david | last post by:
Hello! I've a link error problem problem with VS .NET 2003. I give you the complete description of a simple test (to simplify) : First, I make a WIN32 static library supporting MFC and using...
2
by: Lokicer | last post by:
Hi I note there are two functions putch() and _putch() in VC++ Library. Which one should be used under specified situation. What is the difference between putch() and _putch()? Thanks!
53
by: Deniz Bahar | last post by:
I know the basic definition of a sequence point (point where all side effects guaranteed to be finished), but I am confused about this statement: "Between the previous and next sequence point an...
0
by: Martin Aliger | last post by:
Hi all, is there any way how to access type which is decorated with mine attribute within that attribute? E.g. public class Whatever {
0
by: Prodip Saha | last post by:
Sorry about the cross-posting but I need to get attention from the ADO.Net and Web Service Gurus! I really need to use the System.Data.OleDb.OleDbParameter Class but I am getting following error...
6
by: seb | last post by:
Hi, I am using pygtk for the first times. I am wondering what would be the best "pattern" to interface pygtk with a thread. The thread is collecting informations (over the network for...
8
by: Viktor | last post by:
Can somebody give me an explanation what happened here (or point me to some docs)? Code: HMMM = None def w(fn): print 'fn:', id(fn) HMMM = fn
10
by: =?Utf-8?B?UGF0cmljayBXZXN0ZXJob2Zm?= | last post by:
Hello, I'm currently working on a small DLL that will be used as an extension to a working application. It is required that the DLL has only one export named "C16_DLLCALL". So I started creating...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
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: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.