[RFC] Parametric Polymorphism

Catalin Marinas catalin.marinas at gmail.com
Sun Sep 25 13:18:21 CEST 2005

"Diez B. Roggisch" <deets at nospam.web.de> wrote:
> google for gnosis utils and multimethods to see a more "oldfashioned"
> implementation.

I now remember to have seen it but it requires a lot of typing to
achieve it and you would call a different function name from the one
you define, reducing the code clarity.

> But your approach certainly is interesting - however,

The idea is not new. Lisp/CLOS implements the defmethod macro which
creates a generic function (i.e. a dispatcher) with the same name as
the function you define:
http://www.lisp.org/HyperSpec/Body/mac_defmethod.html. Actually, the
defmehod macro is the base for implementing object polymorphism.

> I _rarely_ need such functionality. Ususally duck-typing suits me
> well.

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

Another use case is to extended the functionality of a class using
functions but you cannot easily modify the class or create a subclass
(the objects are generated by some factory implemented in a
third-party library). Of course, you might be able to get around this
but parametric polymorphism could reduce the written code.

This idea only needs an optimised (and deterministic) implementation
for the best parameter match based on subclass-superclass
relations. It can also be extended to implement polymorphism based on
the parameter values (something people tried to do in C++ with
complicated templates but, well, only at compilation time, with
obvious drawbacks).


More information about the Python-list mailing list