[Tutor] Decision matrix

Jeff Shannon jeff@ccvcorp.com
Fri Feb 14 13:30:02 2003


Erik Price wrote:

>
> On Thursday, February 13, 2003, at 08:03  PM, Jeff Shannon wrote:
>
>> Yes.  Python has quite a number of informal protocols, and any object 
>> that supports certain actions is said to conform to that protocol.  [...]
>
>
> I see.  So these are protocols that have come up via convention, i.e. 
> there is no standard by which to implement the protocol?  They have 
> just come about from familiarity?
>
> Or is there somewhere in the StdLib that specifies how implementations 
> of, say, file-like objects should behave.


Well, the specification of how file-like objects should behave is, in 
essence, the standard file object.  In Python, protocols are just a 
fancy way of saying "If it walks like a duck, and quacks like a duck, 
then it's a duck."  Python doesn't care whether it's a naturally-born 
barnyard duck or a cybernetic Terminator-duck, as long as it looks and 
acts in the way that is expected.  So if you want an object that'll 
imitate a file, and be usable where files are usable, then you look at 
what files do, and make an object that does the same things.  In 
general, you can look at the Python docs to see what methods files have, 
and write the same methods yourself.  

There are some cases where it'd be nice to have more complete protocol 
docs, though.  For example, there's a few common operations on lists, 
but to have a fully list-like object you also need to support len(), and 
slicing, and a few other assorted details.  It'd be nice to have a 
complete list of those details, and any magic methods needed to 
implement them.  I seem to remember some discussion quite a while ago on 
c.l.py (back when I had time to read that ;) ) about formalizing a 
number of protocols, and there may even have been a PEP submitted, but I 
don't recall any real resolution to the discussion...

Jeff Shannon
Technician/Programmer
Credit International