473,385 Members | 1,642 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,385 software developers and data experts.

Trouble with metaclass

Hi,

I'm having trouble with a metaclass suposed to check the method signature of
its classes.

Here's the metaclass:

class MetaChecker(type):
def __new__(cls, name, bases, attribs):
for name, value in attribs.iteritems():
if inspect.ismethod(value):
if not isSingleArg(value):
raise "%s is not a thunk method!"%name
return type.__new__(cls, name, bases, attribs)
def isSingleArg(fn):

args = inspect.getargspec(fn)[0]
if len(args) == 1:
return 1
else:
return None
And here's a class with this metaclass:

class Preconditions (object):

__metaclass__ = MetaChecker

If I define a descendant of Preprocesor with a method with 2 arguments, I
don't get any error:
class P (Preprocessor):
def f(self, x):
return x
What am I doing wrong? O:-)

Jul 18 '05 #1
3 1676
Fernando Rodriguez wrote:
Hi,

I'm having trouble with a metaclass suposed to check the method signature of
its classes.

Here's the metaclass:

class MetaChecker(type):
def __new__(cls, name, bases, attribs):
for name, value in attribs.iteritems():
if inspect.ismethod(value):
if not isSingleArg(value):
raise "%s is not a thunk method!"%name
return type.__new__(cls, name, bases, attribs)
def isSingleArg(fn):

args = inspect.getargspec(fn)[0]
if len(args) == 1:
return 1
else:
return None
And here's a class with this metaclass:

class Preconditions (object):

__metaclass__ = MetaChecker

If I define a descendant of Preprocesor with a method with 2 arguments, I
don't get any error:
class P (Preprocessor):
def f(self, x):
return x
What am I doing wrong? O:-)


The problem seems to be with ismethod function. Cf.:

import inspect

class MetaFoo(type):
def __new__(cls, name, bases, attribs):
for name, value in attribs.iteritems():
if inspect.isfunction(value):
print '%s(%s)' % (name, ',
'.join(inspect.getargspec(value)[0])) // Sorry, it's wrapped :(

return type.__new__(cls, name, bases, attribs)

class Base(object):
__metaclass__ = MetaFoo

class Foo(Base):
def method0(self): pass
def method1(self, x): pass
def method2(self, x, y): pass

And compare:

class Foo(object):
def method(self): pass
print 'inside', inspect.ismethod(method)
print 'inside', type(method)

print 'outside', inspect.ismethod(Foo.method)
print 'outside', type(Foo.method)

Python2.3 prints:
inside False
inside <type 'function'>
outside True
outside <type 'instancemethod'>
regards,
anton.

Jul 18 '05 #2
anton muhin wrote:
Fernando Rodriguez wrote: ...
class MetaChecker(type):
def __new__(cls, name, bases, attribs):
for name, value in attribs.iteritems():
if inspect.ismethod(value):

... The problem seems to be with ismethod function. Cf.:


Right, or, more precisely, there is no problem with ismethod -- it
correctly reports that the values in the attribs dictionary are not
method objects (they're function objects).

Summarizing and simplifying only a little bit...:

1. The def statement always and exclusively creates a function object.

2. A function object is also a descriptor: when you call f.__get__(x),
you get back a method object with im_func == f and im_self == x.

3. The attribute lookup process calls x.__get__(self) on any attribute
it may find in the class's dictionary.

But at this point in the execution of the metaclass's __new__, there
is no "class dictionary" yet -- there isn't even a _class_ -- just a
plain dictionary of attributes which will BECOME the class dictionary
once you call type.__new-_ with that dict as the 4th argument.
Alex

Jul 18 '05 #3
Fernando Rodriguez <fr*@easyjob.net> wrote in message news:<jb********************************@4ax.com>. ..
Hi,

I'm having trouble with a metaclass suposed to check the method signature of
its classes.

Here's the metaclass:

class MetaChecker(type):
def __new__(cls, name, bases, attribs):
for name, value in attribs.iteritems():
if inspect.ismethod(value):
if not isSingleArg(value):
raise "%s is not a thunk method!"%name
return type.__new__(cls, name, bases, attribs)
def isSingleArg(fn):

args = inspect.getargspec(fn)[0]
if len(args) == 1:
return 1
else:
return None
And here's a class with this metaclass:

class Preconditions (object):

__metaclass__ = MetaChecker

If I define a descendant of Preprocesor with a method with 2 arguments, I
don't get any error:
class P (Preprocessor):
def f(self, x):
return x
What am I doing wrong? O:-)


The metaclass is right and actually the names you are using (Preconditions/
Preprocessors) suggest to me that you are using the right tool for the job;
the only problem is that you must use 'inspect.isfunction' and not
'inspect.ismethod', because of the methods <=> functions mismatch I am
sure you know everything about ;) If not, please feel free to ask.

Also, I would use

return super(mcl,MetaChecker).__new__(mcl,name,bases,attr ibs)

instead of type.__new__, anticipating the need for multiple inheritance
of metaclasses.
Michele
Jul 18 '05 #4

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

Similar topics

0
by: Robin Becker | last post by:
A colleague wanted to initialize his class __new__ and tried code resembling this #######################1 class Metaclass (type): def __init__(cls, name, bases, *args, **kwargs):...
5
by: Irmen de Jong | last post by:
Hi, I've developed the Metaclass below, because I needed a way to make a bunch of classes thread-safe. I didn't want to change every method of the class by adding lock.aqcuire()..lock.release()...
33
by: Jacek Generowicz | last post by:
I would like to write a metaclass which would allow me to overload names in the definition of its instances, like this class Foo(object): __metaclass__ = OverloadingClass att = 1 att = 3
2
by: zipher | last post by:
After searching through comp.lang.python and the web regarding metaclasses, I could not find an example for customing classes using metaclass parameters. I want to be able to create a class at...
16
by: ironfroggy | last post by:
Hoping this isn't seeming too confusing, but I need to create a metaclass and a class using that metaclass, such that one of the bases of the metaclass is the class created with that metaclass. I...
14
by: Pedro Werneck | last post by:
Hi I have a class A, with metaclass M_A, and class B, subclass of A, with metaclass M_B, subclass of M_A. A class C, subclass of B must have M_B or a subclass of it as metaclass, but what if...
9
by: Christian Eder | last post by:
Hi, I think I have discovered a problem in context of metaclasses and multiple inheritance in python 2.4, which I could finally reduce to a simple example: Look at following code: class...
4
by: Pedro Werneck | last post by:
Hi all I noticed something strange here while explaining decorators to someone. Not any real use code, but I think it's worth mentioning. When I access a class attribute, on a class with a...
2
by: lbolognini | last post by:
Hi all, I dare risk my brain exploding by reaching for the understanding of metaclasses. At first i thought i almost got them, even if vaguely back in a corner of my mind, my understanding...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.