Yet Another PEP: Query Protocol Interface or __query__

Delaney, Timothy tdelaney at avaya.com
Tue Mar 20 22:06:07 EST 2001


So far as I can see, this PEP does not solve one basic problem - interfaces
which the class writer doesn't know about.

For example, I have an interface, mapped to "org.mydomain.something". Then I
have a slightly different interface mapped to "org.mydomain.somethingelse".

I have a class which implements org.mydomain.something. However, whilst it
can perfectly implement org.mydomain.somethingelse, it would be rejected as
it doesn't actually know about it.

I think it would be better if an interface was actually a class instance
which specified exactly what it required. This could not only be methods (or
other attributes), but also the (minimum) parameters required (and possibly
their types) and even any pre- or post- conditions required by the
interface. It could also mark "optional" features which if available will be
used. FOr example, an interface could specify an optional readlines()
method, but if it is not available the object would still meet the
requirements for the interface if it provided the read() method.

This instance then gets passed to the __query__() method. The __query__()
method then inspects the requirements, and returns either a class instance
or None. The class instance could either be self or a proxy to self or
something completely separate. A None of course means that it cannot meet
the requirements for the interface.

If no __query__() method is defined on the class, the query() function would
then inspect the methods and other attributes of the class to determine if
it meets the requirements of the interface. Naturally, interfaces with
post-conditions would have to fail immediately in this case, and any
pre-conditions which could not be readily determined would also have to fail
the interface test immediately. A "readily-determined" pre-condition would
be something like "attribute x == 3" (not a good example, but a simple one).

This seems to me a much more general and useful way of specifying
interfaces, whilst covering all the things an interface may need. It allows
the __query__() method to return different things on different invocations
for the same interface, depending on the state of the class. For example, a
file-like object may be unable to meet the "file-like" interface until it
has all its data in memory. Until this is the case, it would return None
from its __query__() method for an interface which required the read()
method.

I may well just try implementing this some time ... most of it shouldn't be
too hard. Unfortunately, I've got a nasty deadline coming up ... :(

Tim Delaney
Avaya Australia
+61 2 9352 9079

All recipient(s) of this email have permission to forward or reply to this
email, quoting this email in full or in part.

> Let me see, a string goes in, and an object 
> comes out. Sure.  Looks good to me!




More information about the Python-list mailing list