Mainly Tech projects on Python and Electronic Design Automation.

Wednesday, June 24, 2009

Type based API's and Duck Typing Shocker!!

The Voidspace tech blog has href="">an
article in which the author, Michael Ford, blames duck-typing
for 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 by
stating the principal of duck typing as:

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

All well and good but then later on Michael states:

"If we
want our code to treat different types of object differently then
the approach in example two fails. This isn't contrived - this is
exactly 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 duck
typings 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 a
pain, but I think the cause of the problem w.r.t. duck typing is
choosing an API that relies on an ill-defined idea of what constitutes
close enough to a dict/list/string or whatever, then not having the
language provide an easy solution.

base classes
are an attempt to help out in such cases that is
new in Python 2.6 and 3.0, but if you want to link functionality with
type 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 depends
on an  attribute of an argument, then it may be wise to check
all arguments for compatibility up-front; but even then, whats wrong
with reading the code?  Defensive programming can creep up on

No comments:

Post a Comment


Subscribe Now: google

Add to Google Reader or Homepage

Go deh too!

Blog Archive