A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://mail.python.org/pipermail/python-dev/2002-October/029033.html below:

[Python-Dev] Re: proposal for interfaces

[Python-Dev] Re: proposal for interfacesGerald S. Williams gsw@agere.com
Tue, 1 Oct 2002 13:48:11 -0400
I'm not sure why you'd need a new keyword for this feature when you can
simply create a class that can check if methods in a derived class have
been implemented. You can also check for other attributes if you use a
live object instead of a class. All it needs to do is raise an exception
if the interface isn't fully implemented.

Here is an (admittedly simplified) example:

    import types
    from exceptions import TypeError

    class Interface(object):
        def implemented_by(self,implementer):
            # Verify against class methods:
            methods = []
            for i in dir(self.__class__):
                if i not in dir(Interface):
                    methods.append(i)
            for i in methods:
                if i not in dir(implementer):
                    raise TypeError, "%s not implemented" % str(i)
                # and verify its type, parameters, ...

            # For objects, can also verify that attributes created in the
            # interface's __init__ exist:
            if type(implementer) not in (type(Interface), types.ClassType):
                # Assume it's an object. There's probably a better way.
                # (type(implementer) is types.ObjectType) works, but only
                # for new-style classes.
                methods += dir(Interface)
                attributes = []
                for i in dir(self):
                    if i not in methods:
                        attributes.append(i)
                for i in attributes:
                    if i not in dir(implementer):
                        raise TypeError, "%s not implemented" % str(i)

Something as simple as this would let you verify that a class or object
has implemented an interface. For example:

    class TestInterface(Interface):
        def __init__(self):
            # object attributes to look for:
            self.attrib = "Some attribute"
        # class methods to look for:
        def method(self):
            "Some method"

    # To verify only methods, check the class
    TestInterface().implemented_by(Foo)

    # To verify attributes, check an object
    TestInterface().implemented_by(Foo())

I don't know what Zope does, but this doesn't seem that ugly to me.

-Jerry



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4