[Python-3000] Python-3000 Digest, Vol 9, Issue 27

Bill Janssen janssen at parc.com
Wed Nov 15 04:46:39 CET 2006


> The real
> problem is that iterator is an interface, and there's no formal way to
> express interfaces in Python; it's all in the documentation.
> ...
> The problem with .__getitem__ is, you can't tell whether an object is
> a sequence or a mapping.  If it has .__getitem__, it's one or the
> other, but you don't know whether it accepts sequential integers
> starting from 0, or arbitrary keys.

Actually, Mike, there is a formal way to express interfaces in Python.

We just don't use it.

The mechanism is to define all interfaces clearly as base types, and
use the type mechanism to indicate "typeness" instead of the pervasive
use of duck-typing.  Then, to indicate that a type "implements" the
"foo" interface, just inherit from "foo".

But wait, there's more!  Since Python usefully supports multiple
inheritance in way that Java doesn't, Python "interface" classes can
actually provide useful generic implementations of functionality,
where possible, or raise NotImplemented where not possible.

And that's not all!  You could then see if a value implements a
particular interface with isinstance(), instead of having to check for
the presence of "__getitem__", and wondering if the implementor's
"__getitem__" is the same "__getitem__" you were thinking of.
Suddenly you can do non-fragile reflective programming.

Bill


More information about the Python-3000 mailing list