[Types-sig] Re: [Python-Dev] Revive the types sig?

Guido van Rossum guido@digicool.com
Mon, 12 Mar 2001 09:00:49 -0500


[Responses trimmed]

[Ping]
> For the record, here is a little idea i came up with on the
> last day of the conference:
> 
> Suppose there is a built-in class called "Interface" with the
> special property that whenever any immediate descendant of
> Interface is sub-classed, we check to make sure all of its
> methods are overridden.  If any methods are not overridden,
> something like InterfaceException is raised.
> 
> This would be sufficient to provide very simple interfaces,
> at least in terms of what methods are part of an interface
> (it wouldn't do any type checking, but it could go a step
> further and check the number of arguments on each method).
> 
> Example:
> 
>     >>> class Spam(Interface):
>     ...     def islovely(self): pass
>     ...
>     >>> Spam()
>     TypeError: interfaces cannot be instantiated
>     >>> class Eggs(Spam):
>     ...     def scramble(self): pass
>     ...
>     InterfaceError: class Eggs does not implement interface Spam
>     >>> class LovelySpam(Spam):
>     ...     def islovely(self): return 1
>     ...
>     >>> LovelySpam()
>     <LovelySpam instance at ...>
> 
> Essentially this would replace the convention of writing a
> whole bunch of methods that raise NotImplementedError as a
> way of describing an abstract interface, making it a bit easier
> to write and causing interfaces to be checked earlier (upon
> subclassing, rather than upon method call).
> 
> It should be possible to implement this in Python using metaclasses.

You could do this in pure Python using meta-classes.

This could go some way towards enforcement of interfaces at the
implementation side, but I'm not even sure that that's the real
issue.

I think enforcement is required more at the call side -- if I expect
something that implements interface Foo, I need to be able to
efficiently write and execute a type assertion about that.  At this
point, I'm probably happy to take anything that *says* it implements
Foo -- if it doesn't implement some Foo method, I'll find out sooner
or later.

But that's shallow anyway.  The deep(er) part is whether the object
passed in *thinks of itself* as implementing the Foo interface.  This
means that its author has (presumably) spent at least a little time
about the invariants that a Foo should obey.  The enforcement class
you propose does't help there.

--Guido van Rossum (home page: http://www.python.org/~guido/)