Defining a protocol as a subset of an existing type

protocolForType( baseType, [methods=(), implicit=False])
Return a protocol object that represents the subset of baseType denoted by methods. It is guaranteed that you will receive the same protocol object if you call this routine more than once with eqivalent paremeters. This behavior is preserved even across pickling and unpickling of the returned protocol object.

baseType should be a type object, and methods should be a sequence of attribute or method names. (The order of the names is not important.) The implicit flag allows adapting objects that don't explicitly declare support for the protocol. (More on this later.)

Typical usage of this function is to quickly define a simple protocol based on a Python built-in type such as list, dict, or file:

\begin{verbatim}IReadFile = protocols.protocolForType(file, ['read','close'])
IReadMapping = protocols.protocolForType(dict, ['__getitem__'])

The advantage of using this function instead of creating an Interface subclass is that users do not need to import your specific Interface definition. As long as they declare support for a protocol based on the same type, and with at least the required methods, then their object will be considered to support the protocol. For example, declaring that you support protocolForType(file, ['read','write','close']) automatically implies that you support protocolForType(file, ['read','close']) and protocolForType(file, ['write','close']) as well. (Note: instances of the baseType and its subclasses will also be considered to provide the returned protocol, whether or not they explicitly declare support.)

If you supply a true value for the implicit flag, the returned protocol will also adapt objects that have the specified methods or attributes. In other words, protocolForType(file, ['read','close'], True) returns a protocol that will consider any object with read and close methods to provide that protocol, as well as objects that explicitly support protocolForType(file, ['read','close']).

In order to automatically declare the relationships between the protocols for different subsets, this function internally generates all possible subsets of a requested methods list. So, for example, requesting a protocol with 8 method names may cause as many as 127 protocol objects to be created. Of course, these are generated only once in the lifetime of the program, but you should be aware of this if you are using large method subsets. Using as few as 32 method names would create 2 billion protocols!

Note also that the supplied baseType is used only as a basis for semantic distinctions between sets of similar method names, and to declare that the baseType and its subclasses support the returned protocol. No protocol-to-protocol relationships are automatically defined between protocols requested for different base types, regardless of any subclass/superclass relationship between the base types.