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

alan.gauld@bt.com alan.gauld@bt.com
Fri Feb 14 07:50:02 2003


> 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
> 

Absolutely it would be more sensible to write something like:

# the foo method expects an object supporting the readline() call
def foo(bar):
   return bar.readline()

and of course it should be a doc string rather than a comment! :-)

> Or is that something that people who are concerned with robust/secure 
> code do in fact do?  

How does it make it any more robust?
If the object supports the entire interface used by the function 
internals then its going to be robust. Rather than an if check 
you should in production code wrap the function implenetaion with a
try/except:

def foo(bar):
   try:
       return bar.readline()
   except AttributeError:
       # Do whatever seems sensible...
       raise

> very strong argument against strongly-typed languages with 
> well-defined interfaces, so I was wondering if anyone has any other tips 
> on this topic?

As a vociferous proponent of strongly typed languages(pre Python) I am 
surprised how well Pythons run time approach works. I certainly don't 
see any more faults in my Python code that in my C++ code, and I write 
a lot less.

Interestingly the few objective studies that exist suggest that regardless 
of language, for any given programmer there is a pretty constant ratio 
of bugs to lines of code. Therefore the best way to reduce bugs is reduce 
the lines of code needed! Python achieves just that...

Alan G.