duck-type-checking?

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Nov 15 03:50:33 EST 2008


On Sat, 15 Nov 2008 20:00:03 +1300, greg wrote:

> Joe Strout wrote:
> 
>> So, in this case, the simplest solution was to have the method that
>> initially accepts and stores the data check to make sure that data
>> satisfies the assumptions of the class.
> 
> In hindsight, yes, but the trouble is that you can't tell ahead of time
> which of the gazillion places in the code that where you store things
> away in containers are likely to cause a problem later.
> 
> I can't imagine myself writing code to check every argument to every
> method to guard against this sort of thing. 

Which is, of course, the weakness of dynamic typed languages like Python. 
With statically typed languages like Pascal and C, you can get the 
compiler to check that for you (often at compile time), but at the cost 
of a lot more effort up front. And with languages like Haskell, the type 
inference engine can do much of that type checking without you needing to 
make explicit type declarations.


> If you're willing to do
> that, it's up to you, but it's far from common practice in Python
> programming.

True. It's generally more efficient for the programmer's time to let the 
function or method fail where ever it happens to fail, rather than trying 
to get it to fail up front. But the cost of this is that sometimes it's 
*less* efficient for the programmer, because he has no idea where the 
offending object was injected into the code.

I wonder whether the best solution is to include all your type checks 
(isinstance or duck-typing) in the unit tests, so you can avoid paying 
the cost of those tests at runtime? If your code passes the unit tests, 
but fails with real data, then your unit tests aren't extensive enough.



-- 
Steven



More information about the Python-list mailing list