473,804 Members | 2,225 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 1364
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
1995
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
937
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
1404
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
1580
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
2289
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
7
2286
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
996
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
2209
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
966
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
10603
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
10353
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
10099
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
9176
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
6869
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
5536
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
5675
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4314
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
3
3003
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.