473,796 Members | 2,522 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 misunderstandin g
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 1681
On Aug 21, 9:22*pm, robert2821 <robert2...@ver izon.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 misunderstandin g
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(objec t):

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__.tes t instance at 0x009FEE18__mai n__.test
<bound method ?.docall of <__main__.tes t instance at 0x009FEE18>>
in __get__ <__main__.tes t instance at 0x009FEE18__mai n__.test
(<__main__.tes t 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
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...
10
2221
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
2354
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
2501
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
1305
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
4783
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
1954
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
1060
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
9685
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
10459
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10187
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 most users, this new feature is actually very convenient. If you want to control the update process,...
0
10018
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9055
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...
1
7553
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5446
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
5578
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2928
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.