473,803 Members | 3,416 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Wrapping method calls with metaclasses

I've never used metaclasses in real life before and while searching through
the online Cookbook I found this gorgeous example:

"Wrapping method calls (meta-class example)"
http://aspn.activestate.com/ASPN/Coo.../Recipe/198078

What I want to do in my app is to log all method calls and seems that the
metaclass example above do this fine but it fails when it's needed to
instantiate the class I'm in in a method. So if I do:

class Test(object):
__metaclass__ = LogTheMethods
def foo(self):
return Test()

this generate a Runtime Error cause recursion never stops :(
Any hint to enhance the example?
--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
Dec 6 '05 #1
4 1804
Lawrence Oluyede <ra***@dot.co m> wrote:
I've never used metaclasses in real life before and while searching through
the online Cookbook I found this gorgeous example:

"Wrapping method calls (meta-class example)"
http://aspn.activestate.com/ASPN/Coo.../Recipe/198078

What I want to do in my app is to log all method calls and seems that the
metaclass example above do this fine but it fails when it's needed to
instantiate the class I'm in in a method. So if I do:

class Test(object):
__metaclass__ = LogTheMethods
def foo(self):
return Test()

this generate a Runtime Error cause recursion never stops :(
Any hint to enhance the example?


I can't reproduce the infinite recursion you observe, by merging said
recipe and your definition of class Test, w/Python 2.4.2 on Mac OS 10.4.

Can you please supply a minimal complete example, e.g. simplifying
function logthemethod to just emit s/thing to stdout etc, that does
exhibit the runaway recursion problem you observe?
Alex
Dec 7 '05 #2
Il 2005-12-07, Alex Martelli <al***@mail.com cast.net> ha scritto:
I can't reproduce the infinite recursion you observe, by merging said
recipe and your definition of class Test, w/Python 2.4.2 on Mac OS 10.4.


It seemed that the problem arose because I was not using super() in a new
style class based hierarchy.

class Test(object):
__metaclass__ = LogTheMethods
logMatch = '.*'

def __init__(self, foo):
self.foo = foo

def test(self):
return "test"

class TestChild(Test) :
def __init__(self):
# with super this works
Test.__init__(s elf, "foo")

def test(self):
return "child"

d = {'test': Test,
'child': TestChild}

class MainTest(object ):
__metaclass__ = LogTheMethods
logMatch = '.*'

def create_test(sel f, key):
return d[key]()

if __name__ == '__main__':
l = MainTest()
print l.create_test(" child").test()
look in TestChild's __init__(). Not using super() fails with a

"""
File "/home/rhymes/downloads/simple_logger.p y", line 55, in __init__
Test.__init__(s elf, "foo")
File "/home/rhymes/downloads/simple_logger.p y", line 24, in _method
returnval = getattr(self,'_ H_%s' % methodname)(*ar gl,**argd)
TypeError: __init__() takes exactly 1 argument (2 given)
"""

In my project I'm doing deeply nested recursion things and it exceeds the
maximum recursion limit for this problem this way.

I don't get to fully work the metaclass anyway for other weird reasons
(using super() I lose an attribute around?!) I'm gonna fix this.
--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
Dec 7 '05 #3
Il 2005-12-07, Lawrence Oluyede <ra***@dot.co m> ha scritto:
I don't get to fully work the metaclass anyway for other weird reasons
(using super() I lose an attribute around?!) I'm gonna fix this.


It was a bug of one of the super() in the chain.
Still suffer from deep recursion limit error with that metaclass.
Keep trying.
--
Lawrence - http://www.oluyede.org/blog
"Anyone can freely use whatever he wants but the light at the end
of the tunnel for most of his problems is Python"
Dec 7 '05 #4
Lawrence Oluyede wrote:
look in TestChild's __init__(). Not using super() fails with a

"""
File*"/home/rhymes/downloads/simple_logger.p y",*line*55,*in *__init__
Test.__init__(s elf,*"foo")
File*"/home/rhymes/downloads/simple_logger.p y",*line*24,*in *_method
returnval*=*get attr(self,'_H_% s'*%*methodname )(*argl,**argd)
TypeError: __init__() takes exactly 1 argument (2 given)
"""


The problem with the recipe seems to be that the mangled _H_XXX() method is
always looked up in the child class. One fix may be to store the original
method in the wrapper instead of the class:

def logmethod(metho dname, method):
def _method(self,*a rgl,**argd):
global indent

#parse the arguments and create a string representation
args = []
for item in argl:
args.append('%s ' % str(item))
for key,item in argd.items():
args.append('%s =%s' % (key,str(item)) )
argstr = ','.join(args)
print >> log,"%s%s.%s(%s ) " %
(indStr*indent, str(self),metho dname,argstr)
indent += 1
# do the actual method call
returnval = method(self, *argl,**argd)
indent -= 1
print >> log,'%s:'% (indStr*indent) , str(returnval)
return returnval

return _method
class LogTheMethods(t ype):
def __new__(cls,cla ssname,bases,cl assdict):
logmatch = re.compile(clas sdict.get('logM atch','.*'))

for attr,item in classdict.items ():
if callable(item) and logmatch.match( attr):
classdict[attr] = logmethod(attr, item) # replace method by
wrapper

return type.__new__(cl s,classname,bas es,classdict)

Be warned that I did not thoroughly test that.

Peter

Dec 7 '05 #5

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

Similar topics

13
1485
by: Jeremy Sanders | last post by:
Is it possible to implement some sort of "lazy" creation of objects only when the object is used, but behaving in the same way as the object? For instance: class Foo: def __init__(self, val): """This is really slow.""" self.num = val
2
1591
by: Andrzej Kaczmarczyk | last post by:
Hi I am experiencing something weird. maybe you could help me. I have two ineditable classes from outsource libraries: DataColumn and GridColumn I have built a wrapper class around DataColumn like this: public class MyDataColumn {
2
2690
by: =?Utf-8?B?S2lrZQ==?= | last post by:
Hello, I need to be able to somehow wrap calls made through a standard Interface used to access a WCF service. The reason for this is to have a higher degree of control, mainly to catch all kinds of exceptions transperently, and maybe translate them to other exception types. I've tried to wrap the interface with a class but that way I can only invoke methods of the interface passing a string to an execute method...
6
1549
by: mh | last post by:
I am instantiating a class A (which I am importing from somebody else, so I can't modify it) into my class X. Is there a way I can intercept or wrape calls to methods in A? I.e., in the code below can I call x.a.p1() and get the output
0
9703
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
10550
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
10317
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...
1
10295
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
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
5501
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
5633
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4275
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
2972
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.