473,769 Members | 2,240 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 "fooDecorat or"

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 2282
"MR" <pt**********@g mail.comescribi ó en el mensaje
news:11******** **************@ l53g2000cwa.goo glegroups.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 "fooDecorat or"

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 "fooDecorat or"

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.updat e_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.or g...
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.comes cribió en el mensaje
news:11******** **************@ 51g2000cwl.goog legroups.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**********@g mail.comescribi ó en el mensaje
news:11******** **************@ l53g2000cwa.goo glegroups.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 "fooDecorat or"

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 "fooDecorat or"

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.updat e_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
2072
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 looked like about 20:20 split on the following syntaxes: 1 def func(arg1, arg2, arg3) : function... 2 def func(arg1, arg2, arg3): function...
17
1778
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. Previously, when looking at: some_python(code) and_some_more = stuff there was no need to look at the the first line in order to know what
10
2217
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 have a decorator syntax. What is the compelling reason to invent a new one? And if we do, what's to become of the old one? Here's my take on this. We have two kinds of decorators: those that are informational only (like __author__ and...
2
1708
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 to accept it would be to pacify the supporters of the proposal, and that just isn't a good enough reason in language design. However, it got pretty darn close! I'm impressed with how the community managed to pull together and face the enormous...
0
2351
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 Methods Version: $Revision: 1.34 $ Last-Modified: $Date: 2004/09/03 09:32:50 $ Author: Kevin D. Smith, Jim Jewett, Skip Montanaro, Anthony Baxter
13
2360
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
2497
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 was looking into decorators. The examples from PEP 318 http://www.python.org/peps/pep-0318.html#examples don't work - AFAIK because:
2
1953
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 file when I import it? Or perhaps anyway to find the decorators by loading the file by other methods (with out simply parsing it by hand). Basically what I'm looking for is a way to, given a python file, look through that file and find all the...
0
1059
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 those "def" statements inside a "class" statement define functions, not methods. In that sense almost every Python programmer is wrong too: in this example class X:
0
9590
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10051
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 captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8879
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5310
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3968
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
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.