Trouble with metaclass

anton muhin antonmuhin.REMOVE.ME.FOR.REAL.MAIL at rambler.ru
Thu Nov 13 07:42:19 EST 2003


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.





More information about the Python-list mailing list