|
Re: Interfaces or Abstract Base Classes?
|
Posted: Aug 14, 2005 12:04 PM
|
|
> Not to knock the hard work of another person, but I find > PyProtocols, which is an interface/adaptation system for > Python, to be very cumbersome and difficult to use, > largely *because* of the interfaces portion. I know that > someone can do better than this if they are willing to > consider something *other* than interfaces as the basis > for the system.
Yep. That's why I developed generic functions and the concept of Monkey Typing, which use *operations* as the fundamental concept, rather than interfaces. Alas, Guido considers Monkey Typing to be more complex than interfaces and his type signature stuff, even though it's actually quite a bit simpler. (The implementation is probably of equal complexity to his typing ideas.) Unfortunately, a complete explanation of the theory involved in monkey typing is necessarily complex.
The idea of monkey typing is that you can define the notion of "file-like" by saying that some method of one type is "like" some method of another. Or, at a higher level, you can simply say that one class is "like" another, in the sense that any of its methods with the same names are "like" the methods in the other class.
Or to put it another way, monkey typing is simply a slightly more explicit form of duck typing, in that it requires you to somewhere say what your "walk" method is "like" Duck.walk, or that at least you are "like" a Duck. The same concept can be used to safely subsume adaptation.
Monkey typing also fixes one of the obvious problems with the proposed "file" interface: optional methods or attributes, leading to partial implementations of interfaces. In monkey typing, the unit of declaration is a method or attribute, not an entire interface.
For my own personal purposes, however, I find that extensible generic functions are a better solution than interfaces for most practical problems. Python in fact uses extensible generic functions for many purposes already: copy() and pickle(), for example. If such generic functions were first-class entities in Python, we could use concepts like 'file.read(ob, bytecount)' to do "file reading" on someob, rather than guessing at the semantics of ob.read. But it requires rethinking one's approach to OO.
Thus, I created Monkey Typing as a way to use extensible generic functions by masquerading them as "like" declarations and automatic adaptation, in the context of Guido's type declaration syntax. Also, Monkey Typing solves the problem of extracting interfaces (and therefore generic functions) from *existing* code, which no other solution (generic functions included) can accomplish.
Monkey typing, however, is dependent on type declarations in order to be most effective, which is why I personally prefer to use generic functions where I can, and more primitive techniques where I must. However, if/when Python grows type declarations, I'll certainly work on a monkey typing implementation for it.
|
|