SV: Python Productivity over C++

Huaiyu Zhu hzhu at mars.localdomain
Thu Jun 15 19:28:39 EDT 2000


On 14 Jun 2000 21:45:58 -0400, David Bolen <db3l at fitlinxx.com> wrote:

>Ah, good point - try this variant - I switched to getattr() which
>takes the inheritance into account (you could also write your own
>recursive function that used Instance.__bases__ to look in the
>superclasses).

Wow!  It looks so easy that I can't resist yet another little improvement:

"""
Verify.py - verify a class against a template.  Also indicates where a
method is implemented and prints type mismatch.
Adoped from: 
    Newsgroups: comp.lang.python
    Subject: Re: SV: Python Productivity over C++
    From: David Bolen <db3l at fitlinxx.com>
    Date: 14 Jun 2000 21:45:58 -0400
"""

def verify_class (Reference, Instance):
    import types

    print "Checking %s for conformity with interface %s" % \
          (Instance.__name__,Reference.__name__)

    for method in Reference.__dict__.keys():
        if type(Reference.__dict__[method]) == types.FunctionType:
            try:
                actual_method = getattr(Instance,method)
                if type(actual_method) != types.MethodType:
                    raise TypeError
                else:
                    print "Method %s is implemented in %s" % (
                        method, actual_method.im_class)
            except AttributeError:
                print "Method %s is not implemented" % method
            except TypeError:
                print "Method %s is has a different type" % method

#------------------------------------------------------------------
if __name__ == "__main__":
    class MyInterface:
        def method1():       pass
        def method2():       pass
        def method3():       pass
        def method4():       pass
        def method5():       pass
    
    class MyBase:
        "Actual implementations"
        def method1():       pass
        def method2():       pass
    
    
    class MyDerived(MyBase):
        "Actual implementations"
        def method1():       pass
        def method3():       pass
        method5 = 1

    verify_class(MyInterface,MyBase)
    verify_class(MyInterface,MyDerived)

==================================================================
Result:

Checking MyBase for conformity with interface MyInterface
Method method1 is implemented in __main__.MyBase
Method method3 is not implemented
Method method2 is implemented in __main__.MyBase
Method method5 is not implemented
Method method4 is not implemented
Checking MyDerived for conformity with interface MyInterface
Method method1 is implemented in __main__.MyDerived
Method method3 is implemented in __main__.MyDerived
Method method2 is implemented in __main__.MyBase
Method method5 is has a different type
Method method4 is not implemented





More information about the Python-list mailing list