473,785 Members | 2,219 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Emulate @classmethod using decorator and descriptor

Hello, I was recently learning python decorator and descriptor and
emulated a @classmethod decorator:
class EmuClassMethod( object):
def __init__(self, f=None):
self.f = f
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
def wrapped(*args):
return self.f(klass, *args)
return wrapped

class Test(object):
@EmuClassMethod
def t(cls):
print "I'm %s" % cls.__name__

It worked, and seems that a function decorator works as follows:
# decf is a decorator
@decf
def func():
print 'func'

will be "converted" to:

def func():
print 'func'
func = decf(func)

Is this really the case? Or correct me if i'm wrong. Thanks in advance.

Dec 12 '06 #1
2 1544

WaterWalk wrote:
Hello, I was recently learning python decorator and descriptor and
emulated a @classmethod decorator:
class EmuClassMethod( object):
def __init__(self, f=None):
self.f = f
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
def wrapped(*args):
return self.f(klass, *args)
return wrapped

class Test(object):
@EmuClassMethod
def t(cls):
print "I'm %s" % cls.__name__

It worked, and seems that a function decorator works as follows:
# decf is a decorator
@decf
def func():
print 'func'

will be "converted" to:

def func():
print 'func'
func = decf(func)

Is this really the case? Or correct me if i'm wrong. Thanks in advance.
Yes, the two are equivalent. The documentation is found here:
http://docs.python.org/ref/function.html

But I personally found the explanation for decorators a bit confusing.

Dec 12 '06 #2
On 12 dic, 08:46, "WaterWalk" <toolmas...@163 .comwrote:
Hello, I was recently learning python decorator and descriptor and
emulated a @classmethod decorator:
class EmuClassMethod( object):
def __init__(self, f=None):
self.f = f
def __get__(self, obj, klass=None):
if klass is None:
klass = type(obj)
def wrapped(*args):
return self.f(klass, *args)
return wrapped

class Test(object):
@EmuClassMethod
def t(cls):
print "I'm %s" % cls.__name__
Basically you're right. But note that @classmethod does some additional
work to keep the details: the function name is now "wrapped", no
docstring, no argument names, no defaults, wrong type...
>>class Test2(object):
.... @EmuClassMethod
.... def t2(cls, arg1, arg2=2):
.... "t2 docstring"
.... print "I'm %s arg1=%s arg2=%s" % (cls.__name__, arg1, arg2)
....
>>print Test2.t2
<function wrapped at 0x00AB30B0>
>>print Test2.t2.func_n ame
wrapped
>>print Test2.t2.__doc_ _
None
>>print Test2.t2.func_d efaults
None
>>Test2.t2(10 0)
I'm Test2 arg1=100 arg2=2
>>Test2.t2(arg1 =100)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: wrapped() got an unexpected keyword argument 'arg1'

--
Gabriel Genellina

Dec 12 '06 #3

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

Similar topics

14
2315
by: Sandy Norton | last post by:
If we are going to be stuck with @decorators for 2.4, then how about using blocks and indentation to elminate repetition and increase readability: Example 1 --------- class Klass: def __init__(self, name):
3
2429
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!
2
1682
by: Jeffrey Froman | last post by:
Consider the following class: class Node(object): def __init__(self, name, parent=None): self.name = name self.parent = parent def _ancestors(self, ants=None): if ants is None: ants =
0
1097
by: Eric Huss | last post by:
I'm trying to write a descriptor (similar to the EiffelDescriptor example in the Demo directory). However, I noticed an odd behavior that descriptors written in pure Python mask the underlying object they are wrapping, whereas the descriptors written in C do not. For example, taking the code from http://users.rcn.com/python/download/Descriptor.htm which implements what one would think is a straightforward implementation: class...
10
1577
by: sysfault | last post by:
Does anyone know of any good documentation on these topics, doesn't look like the official python tutorial covers them. Thanks in advance. -- A wise man knows he knows nothing.
13
1784
by: Lad | last post by:
I use Python 2.3. I have heard about decorators in Python 2.4. What is the decorator useful for? Thanks for reply L.
3
1096
by: Gary Stephenson | last post by:
I want to define a class-level attribute that will be shared by all subclasses. That is, I want this class, every subclass of this class, every instance of this class and every instance of every subclass to be able to read and write to the _same_ slot/variable. But I can't figure out how to do it. My attempts so far have led me to using a descriptor as follow, but it doesn't get me where I want to be: class sharedClassVar(object):
25
2592
by: samjnaa | last post by:
Please check for sanity and approve for posting at python-dev. In Visual Basic there is the keyword "with" which allows an object- name to be declared as governing the following statements. For example: with quitCommandButton .enabled = true .default = true end with
25
1453
by: Dmitry S. Makovey | last post by:
Hi, after hearing a lot about decorators and never actually using one I have decided to give it a try. My particular usecase is that I have class that acts as a proxy to other classes (i.e. passes messages along to those classes) however hand-coding this type of class is rather tedious, so I decided to use decorator for that. Can somebody tell me if what I'm doing is a potential shot-in-the-foot or am I on the right track? (Note, It's...
0
10346
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...
0
10157
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
9956
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...
1
7504
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
5386
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
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
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
3658
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2887
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.