Python and generic programming

Phillip J. Eby pje at telecommunity.com
Sat Dec 4 01:08:41 CET 2004


Ian Bicking <ianb at colorstudy.com> wrote in message news:<mailman.6643.1100939117.5135.python-list at python.org>...
> Jive Dadson wrote:
> > If you have, for example, several data-types for matrices, how do you
> > write code that will automatically find the right routine for quickly
> > multiplying a vector by a diagonal matrix represented as a vector, and
> > automatically call the right code for multiplying by a sparse matrix
> > represented by some sparse coding, etc?
> 
> I haven't been following this thread, but Phillip Eby's recent 
> implementation of generic functions should be mentioned if it hasn't 
> been already:
> 
> http://dirtsimple.org/2004/11/generic-functions-have-landed.html
> 
> It might look something like this:
> 
> @dispatch.on('m1', 'm2')
> def matrix_mul(m1, m2):
>      "Multiply two matrices"
> 
> @matrix_mul.when(VectorMatrix, SparseMatrix)
> def matrix_mul_sparse(m1, m2):
>      "Special implementation"

Actually, it would be more like:

@dispatch.generic()
def matrix_mul(m1, m2):
    """Multiply two matrices"""

@matrix_mul.when("m1 in VectorMatrix and m2 in SparseMatrix")
def matrix_mul_sparse(m1, m2):
    """Special implementation"""

The 'dispatch.on()' decorator is for single-dispatch functions only. 
If you want to dispatch on multiple arguments or on logical
conditions, you use 'dispatch.generic()'.  The implementations for
single and multiple dispatch are completely separate, and use
different algorithms.



More information about the Python-list mailing list