473,287 Members | 1,515 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,287 software developers and data experts.

About Michele Simionato's "classinitializer" 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 classinitializer "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("__metaclass__", 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 classinitializer(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("__metaclass__", 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["__metaclass__"] = makecls
else:
proc(*args, **kw)
newproc.__name__ = proc.__name__
newproc.__module__ = proc.__module__
newproc.__doc__ = proc.__doc__
newproc.__dict__ = proc.__dict__
return newproc

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

@classinitializer
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 1333
On May 26, 7:10 pm, imho <ce...@comeno.itwrote:
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 classinitializer "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.itwrote:
>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 classinitializer "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
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...
0
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)...
6
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...
10
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
by: Kay Schluehr | last post by:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691
7
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...
2
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...
2
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...
1
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...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 7 Feb 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:30 (7.30PM). In this month's session, the creator of the excellent VBE...
0
by: DolphinDB | last post by:
The formulas of 101 quantitative trading alphas used by WorldQuant were presented in the paper 101 Formulaic Alphas. However, some formulas are complex, leading to challenges in calculation. Take...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: Aftab Ahmad | last post by:
Hello Experts! I have written a code in MS Access for a cmd called "WhatsApp Message" to open WhatsApp using that very code but the problem is that it gives a popup message everytime I clicked on...
0
by: Aftab Ahmad | last post by:
So, I have written a code for a cmd called "Send WhatsApp Message" to open and send WhatsApp messaage. The code is given below. Dim IE As Object Set IE =...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...

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.