[RFC] Parametric Polymorphism

Donn Cave donn at u.washington.edu
Mon Sep 26 12:15:12 EDT 2005


In article <tnxek7dqttu.fsf at arm.com>,
 Catalin Marinas <catalin.marinas at gmail.com> wrote:
...
> Of course, duck-typing is simple to use but the parametric
> polymorphism is useful when the types are unrelated. Let's say you
> want to implement a colour-print function which should support basic
> types like ints and floats as well as lists and dictionaries. In this
> case, and thank to the function decorations support, the code would be
> clearer.

What you're describing (and implementing) is not what I would
call parametric polymorphism, though.  See

http://en.wikipedia.org/wiki/Polymorphism_(computer_science)

You're talking about "ad-hoc" polymorphism.

Personally, I can't agree that, in principle, this practice
makes code clearer.  In more common, less formal implementations
you get functions like this --

   def dosome(cmd):
       if type(cmd) == StringType:
           cmd = [cmd]
       ...

Of course the first problem with this that it unnecessarily
constrains the input type:  if your API supports a string
parameter, then in Python you should expect any value to work
that supports string operations.  This isn't a hypothetical
matter, you can see relatively major Python applications have
trouble with Unicode for exactly this reason.

Secondly, rather than clarify the API, it confuses it.  How
many programmers will observe this usage and erroneously assume
that dosome() _just_ takes a string, when the list parameter
may in fact be the more ideal usage?  This isn't hypothetical
either.

Your example is a fine one, and some kind of table to resolve
the function according to type of input argument is a good idea.
I'm just saying that more general application of this idea is
best left to languages like C++.

   Donn Cave, donn at u.washington.edu



More information about the Python-list mailing list