Trouble with metaclass
Michele Simionato
mis6 at pitt.edu
Thu Nov 13 08:51:25 EST 2003
Fernando Rodriguez <frr at easyjob.net> wrote in message news:<jbq6rvob5qjddbtt6vk97gsr6hk993e6j3 at 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,attribs)
instead of type.__new__, anticipating the need for multiple inheritance
of metaclasses.
Michele
More information about the Python-list
mailing list