473,700 Members | 2,649 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 1357
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
1986
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
931
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
1393
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
1567
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
2281
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
989
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
2203
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
958
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
8725
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
8644
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
8924
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
7807
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
6560
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
5902
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
4656
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3088
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
2392
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.