Yet Another PEP: Query Protocol Interface or __query__

Clark C. Evans cce at clarkevans.com
Wed Mar 21 05:01:50 EST 2001


On Wed, 21 Mar 2001, Huaiyu Zhu wrote:
> Python supports polymorphism in a very liberal way: if it walks like a duck
> and quacks like a duck, then it must be a duck.  The archetypical examples
> is that one can usually substitute a writable file with a user defined class
> object that happens to have a write() methods with appropriate property.

But it's even stronger than that.  In python if all you want is
duck-tracks, a class having a duck-bill isn't required only a 
class having webbed-feet.  ;)
 
> In many programs it is necessary to ensure that a certain objects has
> certain properties.  But how can we express the idea that a function expect
> a file-like object, while that can mean an endless list of things, many have
> not yet been defined?
> 
> One solution promoted by some other languages is to define some abstract
> classes for type checking purpose, and require them to be inherited by any
> class that behaves like them.  This is like what interfaces do in Java.
> This solution is not satisfactory because
> 
> - It breaks polymorphism.  One has to harness the property at the time the
>   classes are defined, instead of when they are used.  For example, if an
>   application requires a property of "ReadableFile" which is satisfied by
>   sys.stdin, it is difficult to retrofit the definition of sys.stdin to be
>   an instance of such.
> 
> - It mixes two incompatible inheritances.  For example, suppose that class A
>   has method A.m() but its subclass B overrides it with B.m().  The property
>   A satisfies is not necessarily satisfied by B.

Yes.  Very insightful.  It is easy to fall into this line of 
thinking and not see the the traps.  I was heasitent when 
I put in the "base class" stuff in the update to the PEP
being promoted.... it just seemed expected.  Perhaps it
isn't the right thing to do.  Once you have classes, 
people like to treat class inheritance as interface
inheritance... 

The rest of your post resonates deeply.  Is there some
way to get a "simple" __query__ mechanism working 
without having the type system in place?  

Clark





More information about the Python-list mailing list