Interfaces in Python (was: [Tutor] checksum of dictionary)

Erik Price eprice@ptc.com
Thu Feb 13 11:47:05 2003


Erik Price wrote:

> Is this in fact how Python works, anybody?  Since it's dynamically 
> typed, I'm not sure how much type really matters anyway, but in library 
> code it might be something to consider.
> 
> In Java there would probably be some interface that the new class could 
> implement so that it can be considered the same type as the dict, yet 
> without actually having to inherit from dict, but that is Java and this 
> is Python, and perhaps types just aren't as significant.  I'm trying to 
> be a more knowledgeable Python programmer so if someone has a pointer to 
> more information on the significance of types in Python... :)

Looks like I just found one:

http://www.artima.com/intv/pycontract.html

Van Rossum seems to suggest that there are plenty of problems that can 
emerge at runtime with a strongly typed language, such as when an object 
is of the appropriate type but does not behave in line with the intent 
of the method it is being passed to.  That in this situation, the only 
thing that will help you is the docs, which is why documentation is so 
crucial to any object.  So, the documentation is actually a better 
advisor to the behavior of an object than any protocol or interface 
could be (in spite of the fact that protocols and interfaces are very 
important to languages like Objective-C or Java).  I take it to mean 
that in Python, concerning oneself with types is just not an issue.  If 
the object does what you want, then use it.

So then is it useless to write code like this:

# the foo method expects a bar object as its argument
def foo(baz):
   if not instanceof(bar, baz):
     raise Exception

Or is that something that people who are concerned with robust/secure 
code do in fact do?  I suppose I should spend more time reading the 
source code of widely-distributed Python software to see how the "pros" 
do it.

To be honest, in the published interview, Van Rossum doesn't provide a 
very strong argument against strongly-typed languages with well-defined 
interfaces, so I was wondering if anyone has any other tips on this topic?



Thanks,

Erik