473,581 Members | 2,757 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Decorator

Lad
I use Python 2.3.
I have heard about decorators in Python 2.4.
What is the decorator useful for?
Thanks for reply
L.

May 12 '06 #1
13 1769
Lad enlightened us with:
I use Python 2.3.
I have heard about decorators in Python 2.4.
What is the decorator useful for?


A whole lot of stuff. I've used them for:
- Logging all calls to a function, including its arguments.
- Ensuring there is a database connection before the function is
called.
- Casting the arguments to certain types before passing them to
the function.

And there is much more possible...

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
May 12 '06 #2
"Lad" <py****@hope.cz > wrote in message
news:11******** **************@ i39g2000cwa.goo glegroups.com.. .
I use Python 2.3.
I have heard about decorators in Python 2.4.
What is the decorator useful for?
Thanks for reply
L.

Check out these examples on the Python wiki:
http://wiki.python.org/moin/PythonDecoratorLibrary

I've gotten to be a big fan of memoize.

-- Paul
May 12 '06 #3
Lad wrote:
I use Python 2.3.
I have heard about decorators in Python 2.4.
What Python 2.4 adds is only syntactic sugar for decorators. You can do
the same - somewhat more explicitely - in 2.3.
What is the decorator useful for?


FWIW, I'm not sure the name 'decorator' is such a great idea. A
decorator (read 'function decorator') is mainly a callable that takes a
callable as param and returns another callable, usually wrapping the
passed callable and adding some responsabilitie s (tracing, logging,
pre-post condition checks, etc). Two well-known examples are classmethod
and staticmethod.

The whole things looks like this:

def deco(func):
print "decorating %s" % func.__name__
def _wrapper(*args, **kw):
print "%s called " % func.__name__
res = func(*args, **kw)
print "%s returned %s" % (func.__name__, str(res))
return _wrapper

# python < 2.4
def somefunc():
print "in somefunc"
return 42

somefunc = deco(somefunc)

The syntactic sugar added in 2.4 allows you to avoid the explicit call
to deco():

# python >= 2.4
@deco
def someotherfunc() :
return "the parrot is dead"
As you see, apart from the syntactic sugar, there's nothing new here.
It's just plain old higher order function, well known in any functional
language.

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 12 '06 #4
"bruno at modulix" schrieb

What Python 2.4 adds is only syntactic sugar for decorators.
You can do the same - somewhat more explicitely - in 2.3.
What is the decorator useful for?

The whole things looks like this:

def deco(func):
print "decorating %s" % func.__name__
def _wrapper(*args, **kw):
print "%s called " % func.__name__
res = func(*args, **kw)
print "%s returned %s" % (func.__name__, str(res))

return res
^^^^^^^^^^
Shouldn't here be a return res, so that wrapper
behaves like the original function?
return _wrapper

# python < 2.4
def somefunc():
print "in somefunc"
return 42

somefunc = deco(somefunc)


Thanks for the explanation.
Another question: Isn't decorating / wrapping usually
done at runtime, so that the @deco notation is pretty
useless (because you'd have to change the original
code)?
What do I miss here?

Martin
May 12 '06 #5
Martin Blume enlightened us with:
Another question: Isn't decorating / wrapping usually done at
runtime, so that the @deco notation is pretty useless (because you'd
have to change the original code)?


Please explain why that would make the @deco notation pretty useless.

Sybren
--
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself?
Frank Zappa
May 12 '06 #6
Martin Blume wrote:
"bruno at modulix" schrieb
(snip)
def deco(func):
print "decorating %s" % func.__name__
def _wrapper(*args, **kw):
print "%s called " % func.__name__
res = func(*args, **kw)
print "%s returned %s" % (func.__name__, str(res))


return res
^^^^^^^^^^
Shouldn't here be a return res, so that wrapper
behaves like the original function?


oops, my bad :(
And yes, of course.
return _wrapper

# python < 2.4
def somefunc():
print "in somefunc"
return 42

somefunc = deco(somefunc)

Thanks for the explanation.
Another question: Isn't decorating / wrapping usually
done at runtime,


It is. I mean, using decorator syntax, this is done during import, which
happens at runtime.
so that the @deco notation is pretty
useless (because you'd have to change the original
code)?
I don't understand your question.
What do I miss here?


Ok, I get it (well, I think...).

The use case for @decorator is for wrapping functions or method *in the
module/class itself*. It's not for module client code (but this of
course doesn't prevent client code to dynamically add other wrappers...)

One of the primary use case makes this pretty clear IHMO : classmethod
and staticmethod :

# python < 2.4:
class Cleese(object):
def doSillyWalk(cls ):
pass
doSillyWalk = classmethod(doS illyWalk)

# python >= 2.4:
class Cleese(object):
@classmethod
def doSillyWalk(cls ):
pass

Another example : CherryPy uses decorators to mark methods which are
'published' (ie: are action controllers responding to a given URL)
HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 12 '06 #7
"Sybren Stuvel" schrieb
Martin Blume enlightened us with:

Don't know if I enlightened anybody ... :-)
Another question: Isn't decorating / wrapping
usually done at runtime, so that the @deco
notation is pretty useless (because you'd
have to change the original code)?


Please explain why that would make the @deco
notation pretty useless.

Well, if you're changing the original module, you
might as well insert the needed functionality in
the original function, no?
Or rename the original function, write a function
having this original name and calling from it the
original functionality?

Isn't the point of a decorator to change the
behavior externally, at runtime, possibly changing
it in different ways at different places at different
times?

So why this @deco notation? Can you apply it externally?
Meaning to
import module
first, then
@deco(module.fu nc)
somewhere later?
Martin

May 12 '06 #8
"bruno at modulix" schrieb

[snip]

The use case for @decorator is for wrapping functions
or method *in the module/class itself*. That was the question. What's the use of doing it
like that in the module *itself* (I mean, you change
directly the original function)?
It's not for module client code (but this of
course doesn't prevent client code to dynamically
add other wrappers...)

How do the clients it? The "oldfashion ed"
deco(doSillyWal k)
way?

Martin


May 12 '06 #9
Martin Blume wrote:
"Sybren Stuvel" schrieb
Martin Blume enlightened us with:
Don't know if I enlightened anybody ... :-)


Not sure...

But let's hope someone else having doubts about @decorator will find
this thread, so we won't have to point him/her to the documentation.
Another question: Isn't decorating / wrapping
usually done at runtime, so that the @deco
notation is pretty useless (because you'd
have to change the original code)?


Please explain why that would make the @deco
notation pretty useless.


Well, if you're changing the original module,


Who's talking about "changing the original module" ?
you
might as well insert the needed functionality in
the original function, no?
higher order functions allow to keep orthogonal responsabilitie s
separated.

(snip)
Isn't the point of a decorator to change the
behavior externally, at runtime, possibly changing
it in different ways at different places at different
times?
You're confusing the python specific @decorator syntax with the OO
design pattern by the same name. This syntax is purely syntactic sugar
for a specific use case of higher order functions.
So why this @deco notation?
To improve readability.

@decorator
def my_one_hundred_ locs_func():
...

is much more readable than:
def my_one_hundred_ locs_func():
...
# 100 LOCS later
my_one_hundred_ locs_func = decorator(my_on e_hundred_locs_ func)
Can you apply it externally?


No. It doesn't make sens to replace:
mymodule.func = decorator(mymod ule.myfunc)
with
@decorator
mymodule.func

Note that all this should be clear for anyone having read the doc...

HTH
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'o****@xiludom. gro'.split('@')])"
May 12 '06 #10

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

Similar topics

11
1624
by: Ville Vainio | last post by:
It might just be that @decorator might not be all that bad. When you look at code that uses it it's not that ugly after all. A lot of the furor about this is probably because it happened so quicly. The situation might have been different if we had seen a pronouncement a week before, in the vein of "I have chosen this syntax - it will go in...
41
2842
by: John Marshall | last post by:
How about the following, which I am almost positive has not been suggested: ----- class Klass: def __init__(self, name): self.name = name deco meth0: staticmethod def meth0(x):
17
1705
by: Jim Jewett | last post by:
Guido has said that he is open to considering *one* alternative decorator syntax. At the moment, (Phillip Eby's suggestion) J4 <URL: http://www.python.org/moin/PythonDecorators > (section 5.21 J4) looks very good to me -- and it is the only alternative without negatives. def func(arg1, arg2) @version("Added in 2.4") @returns(None)
30
2483
by: Ron_Adam | last post by:
I was having some difficulty figuring out just what was going on with decorators. So after a considerable amount of experimenting I was able to take one apart in a way. It required me to take a closer look at function def's and call's, which is something I tend to take for granted. I'm not sure this is 100%, or if there are other ways to...
22
2219
by: Ron_Adam | last post by:
Hi, Thanks again for all the helping me understand the details of decorators. I put together a class to create decorators that could make them a lot easier to use. It still has a few glitches in it that needs to be addressed. (1) The test for the 'function' object needs to not test for a string but an object type instead.
3
2417
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 usefull. Interesting in any case. Making decorators with this class is a snap!
6
1392
by: Michele Simionato | last post by:
could ildg wrote: > I think decorator is a function which return a function, is this right? > e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. > > def accepts(*types): > def check_accepts(f): > assert len(types) == f.func_code.co_argcount
5
1804
by: Doug | last post by:
I am looking at using the decorator pattern to create a rudimentary stored proc generator but am unsure about something. For each class that identifies a part of the stored proc, what if I want to add a value dynamically. I'm including some code to show what I mean. This is real basic on what I want to do: using System; namespace...
4
2466
by: thomas.karolski | last post by:
Hi, I would like to create a Decorator metaclass, which automatically turns a class which inherits from the "Decorator" type into a decorator. A decorator in this case, is simply a class which has all of its decorator implementation inside a decorator() method. Every other attribute access is being proxied to decorator().getParent(). ...
8
2868
by: Chris Forone | last post by:
hello group, is there a possibility to implement the decorator-pattern without new/delete (nor smartpt)? if not, how to ensure correct deletion of the objects? thanks & hand, chris
0
8156
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8310
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7910
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
8180
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
1
5681
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3809
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3832
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2307
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1409
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.