473,602 Members | 2,764 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

About Michele Simionato's "classinitializ er" decorator

Hi all.
I just send this post as a comment to the third part of Michele
Simionato's article about metaprogramming techniques at:

http://www.ibm.com/developerworks/li...GX03&S_CMP=ART
I found extremely useful the classinitialize r "trick". I was thinking
over the caveat not to call a class initializer after the _metaclass_
hook (an exception being raised in that case).
Am I wrong if I state there's a plain solution to this ? I modified the
lines involving "type", replacing it with a custom meta type returned by
a call to frame.f_locals. get("__metaclas s__", type), in such a way the
creation of the class involves the right metaclas, even if it was
defined just before the initializer function:

def classinitialize r(proc):
# basic idea stolen from zope.interface. advice, P.J. Eby
def newproc(*args, **kw):
frame = sys._getframe(1 )
if '__module__' in frame.f_locals and not \
'__module__' in frame.f_code.co _varnames: # we are in a class
thetype = frame.f_locals. get("__metaclas s__", type)
def makecls(name, bases, dic):
try:
cls = thetype(name, bases, dic)
except TypeError, e:
if "can't have only classic bases" in str(e):
cls = thetype(name, bases + (object,), dic)
else: # other strange errs, e.g. __slots__ conflicts
raise
proc(cls, *args, **kw)
return cls
frame.f_locals["__metaclas s__"] = makecls
else:
proc(*args, **kw)
newproc.__name_ _ = proc.__name__
newproc.__modul e__ = proc.__module__
newproc.__doc__ = proc.__doc__
newproc.__dict_ _ = proc.__dict__
return newproc

This makes the trick work even if a metaclass or another
classinitialize r was defined first:

@classinitializ er
def enhance(cls, **kw):
for k, v in kw.iteritems():
setattr(cls, k, v)

class M(type):
pass

class A:
__metaclass__ = M
enhance(x=100)
enhance(y=200)

>>A.x
100
>>A.y
200
>>type(A)
<class '__main__.M'>

What do you think about this solution ?

Diego Novella.
Jun 27 '08 #1
2 1349
On May 26, 7:10 pm, imho <ce...@comeno.i twrote:
Hi all.
I just send this post as a comment to the third part of Michele
Simionato's article about metaprogramming techniques at:

http://www.ibm.com/developerworks/li...a3.html?S_TACT...

I found extremely useful the classinitialize r "trick".
I never use it. Too clever. I am waiting for class decorators
in Python 2.6.
I was thinking
over the caveat not to call a class initializer after the _metaclass_
hook (an exception being raised in that case).
Am I wrong if I state there's a plain solution to this ?
I think your solution is fine. Still, consider waiting for
class decorators ;)

Michele Simionato

Jun 27 '08 #2
Michele Simionato ha scritto:
On May 26, 7:10 pm, imho <ce...@comeno.i twrote:
>Hi all.
I just send this post as a comment to the third part of Michele
Simionato's article about metaprogramming techniques at:

http://www.ibm.com/developerworks/li...a3.html?S_TACT...

I found extremely useful the classinitialize r "trick".

I never use it. Too clever. I am waiting for class decorators
in Python 2.6.
Uhm... I suspected that :-)
>I was thinking
over the caveat not to call a class initializer after the _metaclass_
hook (an exception being raised in that case).
Am I wrong if I state there's a plain solution to this ?

I think your solution is fine. Still, consider waiting for
class decorators ;)

Michele Simionato
Of course, I stand waiting here :-)

Thanks, Diego.

Jun 27 '08 #3

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

Similar topics

17
1980
by: Doug Holton | last post by:
George W Bush, as certified by Florida's election commission. Which decorator syntax do you like the most? See http://wiki.wxpython.org/index.cgi/PythonDecoratorsPoll A. @classmethod def foo(): (82) 14% C1. def foo() : (235) 41% E1. def foo(): @classmethod (260) 45% Total Votes: 577
0
928
by: Michele Simionato | last post by:
I have written a decorator module to make easier to write good decorators (i.e. decorators preserving the signature of the functions they decorate). The documentations contains a (hopefully) nice collections of use cases (which are also test cases, sice I take doctest very seriously ;). You can find it here:
6
1392
by: Michele Simionato | last post by:
could ildg wrote: > I think decorator is a function which return a function, is this right? > e.g. The decorator below if from http://www.python.org/peps/pep-0318.html#id1. > > def accepts(*types): > def check_accepts(f): > assert len(types) == f.func_code.co_argcount
10
1565
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.
19
2275
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
7
2275
by: MR | last post by:
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"
2
987
by: Gerardo Herzig | last post by:
Hi all. I guess i have a conceptual question: Im planing using a quite simple decorator to be used as a conditional for the execution of the function. I mean something like that: @is_logued_in def change_pass(): bla bla And so on for all the other functions who needs that the user is still
2
2198
by: Bighead | last post by:
I remember when I did UI Design in PyQt4 for the first time, I found a manual. In it, no "connect" was used. Instead, an OO approach is applied, new UI classes inherit from old ones, and all the slot functions are automatically connected to some signals, using a decorator. In the __init__ function of our newly written class, "connect" is not invoked. I like this style... Unfortunately, I cannot find that manual now.... So anyone have...
1
956
by: Diez B. Roggisch | last post by:
Hi, I'm using Michele S's decorator-module to create decorators with matching signatures, for better error-catching. However, I now want to enrich the signature of a generic wrapper so that the new function will accept more parameters (keyword only). These additional parameters are consumed by the wrapper and not passed to the decorated function.
0
7993
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
7920
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8401
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
8404
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
8268
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
5867
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
3900
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
3944
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1510
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.