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

Decorators inside of class and decorator parameters

MR
Hello All,

I have a question about decorators, and I think an illustration would
be helpful. Consider the following simple class:

#begin code
class Foo:
def fooDecorator(f):
print "fooDecorator"

def _f(self, *args, **kw):
return f(self, *args, **kw)

return _f

@fooDecorator
def fooMethod(self):
print "fooMethod"

f = Foo()
f.fooMethod()
#end of code

This code runs, and actually serves my purpose. However, I'm a little
confused about three things and wanted to try and work through them
while I had the time to do so. I believe all of my confusion is related
to the parameters related to the fooDecorator:

-how I would pass arguments into the fooDecorator if I wanted to (my
various attempts have failed)
-what the difference is between decorating with @fooDecorator versus
@fooDecorator()
-why does this code even work, because the first argument to
fooDecorator isn't self

I'm searched the net and read the PEPs that seemed relevant, but I
didn't see much about decorators inside of a class like this. Can
anyone comment on any of these three things?

Jan 13 '07 #1
7 2267
"MR" <pt**********@gmail.comescribió en el mensaje
news:11**********************@l53g2000cwa.googlegr oups.com...
I have a question about decorators, and I think an illustration would
be helpful. Consider the following simple class:

#begin code
class Foo:
def fooDecorator(f):
print "fooDecorator"

def _f(self, *args, **kw):
return f(self, *args, **kw)

return _f

@fooDecorator
def fooMethod(self):
print "fooMethod"

f = Foo()
f.fooMethod()
#end of code

This code runs, and actually serves my purpose. However, I'm a little
confused about three things and wanted to try and work through them
while I had the time to do so. I believe all of my confusion is related
to the parameters related to the fooDecorator:
[I reordered your questions to make the answer a bit more clear]
-why does this code even work, because the first argument to
fooDecorator isn't self
fooDecorator is called when the class is *defined*, not when it's
instantiated. `self` has no meaning inside it, neither the class to which it
belongs (Foo does not even exist yet).
At this time, fooDecorator is just a simple function, being collected inside
a namespace in order to construct the Foo class at the end. So, you get
*exactly* the same effect if you move fooDecorator outside the class.
-how I would pass arguments into the fooDecorator if I wanted to (my
various attempts have failed)
Once you move fooDecorator outside the class, and forget about `self` and
such irrelevant stuff, it's just a decorator with arguments.
If you want to use something like this:
@fooDecorator(3)
def fooMethod(self):
that is translated to:
fooMethod = fooDecorator(3)(fooMethod)
That is, fooDecorator will be called with one argument, and the result must
be a normal decorator - a function accepting a function an an argument and
returning another function.

def outerDecorator(param):
def fooDecorator(f):
print "fooDecorator"

def _f(self, *args, **kw):
print "decorated self=%s args=%s kw=%s param=%s" % (self, args, kw,
param)
kw['newparam']=param
return f(self, *args, **kw)

return _f
return fooDecorator

This is the most direct way of doing this without any help from other
modules - see this article by M. Simoniato
http://www.phyast.pitt.edu/~micheles...mentation.html for a better
way using its decorator factory.
-what the difference is between decorating with @fooDecorator versus
@fooDecorator()
Easy: the second way doesn't work :)
(I hope reading the previous item you can answer this yourself)
I'm searched the net and read the PEPs that seemed relevant, but I
didn't see much about decorators inside of a class like this. Can
anyone comment on any of these three things?
As said in the beginning, there is no use for decorators as methods (perhaps
someone can find a use case?)
If you move the example above inside the class, you get exactly the same
results.

HTH,

--
Gabriel Genellina

Jan 14 '07 #2
Gabriel Genellina wrote:
see this article by M. Simoniato
http://www.phyast.pitt.edu/~micheles...mentation.html for a better
way using its decorator factory.
Actually the name is Simionato ;)
I have just released version 2.0, the new thing is an update_wrapper
function similar to the one
in the standard library, but with the ability to preserve the signature
on demand. For instance

def traced(func):
def wrapper(*args, **kw):
print 'calling %s with args %s, %s' % (func, args, kw)
return func(*args, **kw)
return update_wrapper(wrapper, func, create=False)

works exactly as functools.update_wrapper (i.e. copies__doc__,
__module__,etc. from func to wrapper without
preserving the signature), whereas update_wrapper(wrapper, func,
create=True) creates a new wrapper
with the right signature before copying the attributes.

Michele Simionato

Jan 14 '07 #3
Gabriel Genellina wrote:
[snip]
As said in the beginning, there is no use for decorators as methods (perhaps
someone can find a use case?)
Except, perhaps to indicate to the script reader that the decorator only
applies within the class?

Colin W.
If you move the example above inside the class, you get exactly the same
results.

HTH,

Jan 14 '07 #4
"Colin J. Williams" <cj*@sympatico.caescribió en el mensaje
news:eo**********@sea.gmane.org...
Gabriel Genellina wrote:
>As said in the beginning, there is no use for decorators as methods
(perhaps
someone can find a use case?)
Except, perhaps to indicate to the script reader that the decorator only
applies within the class?
But it looks rather strange - a method without self, that is not a
classmethod nor static method, and can't be called on an instance...

--
Gabriel Genellina

Jan 14 '07 #5
"Michele Simionato" <mi***************@gmail.comescribió en el mensaje
news:11**********************@51g2000cwl.googlegro ups.com...
Gabriel Genellina wrote:
>see this article by M. Simoniato
http://www.phyast.pitt.edu/~micheles...mentation.html for a
better
way using its decorator factory.

Actually the name is Simionato ;)
Oh, sorry! I think I've written it wrong in another place too :(

--
Gabriel Genellina

Jan 14 '07 #6
MR
Thanks so much for your reply. You've definitely helped me a great
deal on this. Your comment about the difference between define time and
instantiation time cleared things up more than anything, and that also
helped clear up the confusion I was having about "self".

I think the places I've seen decorators called like fooDecorator() must
be using some default arguments in the function signature...so that
part makes a lot more sense now too.

Thanks again!
Gabriel Genellina wrote:
"MR" <pt**********@gmail.comescribió en el mensaje
news:11**********************@l53g2000cwa.googlegr oups.com...
I have a question about decorators, and I think an illustration would
be helpful. Consider the following simple class:

#begin code
class Foo:
def fooDecorator(f):
print "fooDecorator"

def _f(self, *args, **kw):
return f(self, *args, **kw)

return _f

@fooDecorator
def fooMethod(self):
print "fooMethod"

f = Foo()
f.fooMethod()
#end of code

This code runs, and actually serves my purpose. However, I'm a little
confused about three things and wanted to try and work through them
while I had the time to do so. I believe all of my confusion is related
to the parameters related to the fooDecorator:

[I reordered your questions to make the answer a bit more clear]
-why does this code even work, because the first argument to
fooDecorator isn't self

fooDecorator is called when the class is *defined*, not when it's
instantiated. `self` has no meaning inside it, neither the class to whichit
belongs (Foo does not even exist yet).
At this time, fooDecorator is just a simple function, being collected inside
a namespace in order to construct the Foo class at the end. So, you get
*exactly* the same effect if you move fooDecorator outside the class.
-how I would pass arguments into the fooDecorator if I wanted to (my
various attempts have failed)

Once you move fooDecorator outside the class, and forget about `self` and
such irrelevant stuff, it's just a decorator with arguments.
If you want to use something like this:
@fooDecorator(3)
def fooMethod(self):
that is translated to:
fooMethod = fooDecorator(3)(fooMethod)
That is, fooDecorator will be called with one argument, and the result must
be a normal decorator - a function accepting a function an an argument and
returning another function.

def outerDecorator(param):
def fooDecorator(f):
print "fooDecorator"

def _f(self, *args, **kw):
print "decorated self=%s args=%s kw=%s param=%s" % (self,args, kw,
param)
kw['newparam']=param
return f(self, *args, **kw)

return _f
return fooDecorator

This is the most direct way of doing this without any help from other
modules - see this article by M. Simoniato
http://www.phyast.pitt.edu/~micheles...mentation.html for a better
way using its decorator factory.
-what the difference is between decorating with @fooDecorator versus
@fooDecorator()
Easy: the second way doesn't work :)
(I hope reading the previous item you can answer this yourself)
I'm searched the net and read the PEPs that seemed relevant, but I
didn't see much about decorators inside of a class like this. Can
anyone comment on any of these three things?
As said in the beginning, there is no use for decorators as methods (perhaps
someone can find a use case?)
If you move the example above inside the class, you get exactly the same
results.

HTH,

--
Gabriel Genellina
Jan 14 '07 #7
MR
Wow. Really neat stuff there. memoize seems especially cool since you
can get lots of nice dynamic programming benefits "for free" (sorry if
I just stated the obvious, but I thought was was especially cool.)
Michele Simionato wrote:
Gabriel Genellina wrote:
see this article by M. Simoniato
http://www.phyast.pitt.edu/~micheles...mentation.html for a better
way using its decorator factory.

Actually the name is Simionato ;)
I have just released version 2.0, the new thing is an update_wrapper
function similar to the one
in the standard library, but with the ability to preserve the signature
on demand. For instance

def traced(func):
def wrapper(*args, **kw):
print 'calling %s with args %s, %s' % (func, args, kw)
return func(*args, **kw)
return update_wrapper(wrapper, func, create=False)

works exactly as functools.update_wrapper (i.e. copies__doc__,
__module__,etc. from func to wrapper without
preserving the signature), whereas update_wrapper(wrapper, func,
create=True) creates a new wrapper
with the right signature before copying the attributes.

Michele Simionato
Jan 14 '07 #8

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....
10
by: Paul Morrow | last post by:
Thinking about decorators, and looking at what we are already doing in our Python code, it seems that __metaclass__, __author__, __version__, etc. are all examples of decorators. So we already...
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...
13
by: km | last post by:
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
26
by: Uwe Mayer | last post by:
Hi, I've been looking into ways of creating singleton objects. With Python2.3 I usually used a module-level variable and a factory function to implement singleton objects. With Python2.4 I...
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: Gabriel Genellina | last post by:
En Tue, 29 Jul 2008 08:45:02 -0300, Themis Bourdenas <bourdenas@gmail.com> escribi�: In a very strict sense, I'd say that all those references to "method decorators" are wrong - because...
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...
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: 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:
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
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: 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.