Wednesday, June 24, 2009

The Voidspace tech blog has href="http://www.voidspace.org.uk/python/articles/duck_typing.shtml">anarticle in which the author, Michael Ford, blames duck-typingfor a problem in trying to find the type of an argument.

After a very good explanation of how duck typing in Python comes about Michael starts his section on the problem bystating the principal of duck typing as:

"Theprinciple of duck typing says that you shouldn't care what type ofobject you have - just whether or not you can do the required actionwith your object."

All well and good but then later on Michael states:

"If wewant our code to treat different types of object differently thenthe approach in example two fails. This isn't contrived - this isexactly the situation we found ourselves in with ConfigObj."

So, type is important in his case. Fine. style="font-weight: bold;">But why lay the blame at ducktypings door ?

His example interface relies on knowing what constitutes a "listy"object, or a "stringy" object, etc, in Python 2.x, which he notes is apain, but I think the cause of the problem w.r.t. duck typing ischoosing an API that relies on an ill-defined idea of what constitutesclose enough to a dict/list/string or whatever, then not having thelanguage provide an easy solution.

Abstractbase classes are an attempt to help out in such cases that isnew in Python 2.6 and 3.0, but if you want to link functionality withtype then you can't expect to get duck typing too.

Where Duck Typing Does Not fit.

If a function has an expensive or non-reversible operation that dependson an attribute of an argument, then it may be wise to checkall arguments for compatibility up-front; but even then, whats wrongwith reading the code? Defensive programming can creep up onyou...