473,513 Members | 3,777 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Decorators using instance variables


Hi,

I'm new; greetings all!

I'm wondering if the following program should work. I think it should
print 'Hello, World', but instead it produces a TypeError. Is this a
bug in decorators, a feature of them, or a mistake or misunderstanding
on my part?

TIA, Bob
def getdec (f):
dec = decorator (f)
return dec. docall

class decorator:

def __init__ (self, f):
self. f = f

def docall (self, *a):
return self. f (*a)

class test:
@ getdec
def doit (self, message):
print message

if __name__ == '__main__':
foo = test ()
foo. doit ('Hello, world')


Aug 22 '08 #1
1 1664
On Aug 21, 9:22*pm, robert2821 <robert2...@verizon.netwrote:
Hi,

I'm new; greetings all!

I'm wondering if the following program should work. *I think it should
print 'Hello, World', but instead it produces a TypeError. *Is this a
bug in decorators, a feature of them, or a mistake or misunderstanding
on my part?

TIA, *Bob

def * *getdec (f):
* * dec = decorator (f)
* * return dec. docall

class * *decorator:

* * def __init__ (self, f):
* * * * self. f = f

* * def docall (self, *a):
* * * * return self. f (*a)

class * *test:
* * @ getdec
* * def doit (self, message):
* * * * print message

if __name__ == '__main__':
* * foo = test ()
* * foo. doit ('Hello, world')

*Dec.py
< 1KViewDownload
Have a look at this and fiddle with it:

from types import MethodType
class decorator(object):

def __init__ (self, f):
self. f = f

def docall (self, *a):
print a
return self. f (*a)

def __get__( self, instance, owner ):
print 'in __get__', instance, owner
if instance is not None:
return MethodType( self.docall, instance )
return self.f

class test:
@ decorator
def doit (self, message):
print message

if __name__ == '__main__':
foo = test ()
print test.doit
print foo.doit
foo. doit ('Hello, world')

Output:

in __get__ None __main__.test
<function doit at 0x00A01170>
in __get__ <__main__.test instance at 0x009FEE18__main__.test
<bound method ?.docall of <__main__.test instance at 0x009FEE18>>
in __get__ <__main__.test instance at 0x009FEE18__main__.test
(<__main__.test instance at 0x009FEE18>, 'Hello, world')
Hello, world

The reason is that in the first version, the type of test.doit is
InstanceType, and Python only 'binds' objects of type FunctionType to
MethodType. MethodType is the type that contains an implicit first
'self' parameter. If 'doit' has a __get__ attribute, it is called
whenever -class-.doit or -instance-.doit are accessed, and it returns
a bound method, or something else it likes.

A little more investigating reveals:
>>def f(): pass
...
>>dir( f )
['__call__', '__class__', '__delattr__', '__dict__', '__doc__',
'__get__', '__ge
tattribute__', '__hash__', '__init__', '__module__', '__name__',
'__new__', '__r
...

functions have a '__get__' attribute to perform this very thing.
Aug 22 '08 #2

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

Similar topics

4
2049
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):...
10
2193
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....
2
1697
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...
0
2329
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
26
2470
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:
9
1293
by: Bengt Richter | last post by:
;-) We have @deco def foo(): pass as sugar (unless there's an uncaught exception in the decorator) for def foo(): pass foo = deco(foo) The binding of a class name is similar, and class decorators would seem natural, i.e.,
11
4732
by: Alex Popescu | last post by:
Hi all! I am pretty new to Python, so please excuse me if I am missing something. Lately, I've been playing with decorators and I am a bit confused about some behavior. Here is the code that puzzles me: in python shell: def function(): pass
2
1941
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). ...
0
1044
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...
0
7178
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7397
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
7563
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...
0
7543
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...
0
5703
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...
1
5102
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
4757
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...
0
3252
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...
1
813
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.