generic functions in python

Howard Stearns howard.stearns at charter.net
Sat May 29 14:48:46 EDT 2004


Funny you should mention this today -- I was just sitting down to 
implement generic functions myself. It tends to be the first thing I do 
when learning a new language, and I'm brand new to Python.

My needs are limited, so I'm not thinking past the first pass, in which 
there will be no provision for subclassing your own kinds of 
Generic_Function and no syntactic sugar (e.g, no defmethod, just hand 
intialization at load time of new methods, and hand coordination between 
the function object and the Generic_Function object, and no 
Funcallable_Instance class). Just basic multimethod dispatch with a simple 
cache. As much as I believe Dylan's class precedence linearization is "The 
Right Thing(tm)", I'll just do whatever's easiest for ordering the 
classes. Anyway, I'll know more when I get into it.

When I finish (who knows when?), I'll try to remember to post here and cc 
you, Jim. Please do the same with me if you come up with anything, and 
please ping me after a bit if I forget.



Jim Newton wrote:

> hi all, i'm relatively new to python.  I find it a
> pretty interesting language but also somewhat limiting
> compared to lisp.  I notice that the language does
> provide a few lispy type nicities, but some very
> important ones seem to be missing.
> 
> E.g., the multiple class inheritance is great,
> but there are no generic functions (at least that
> i can find).  If i have classes  X, Y, and Z,
> and subclasses X_sub, Y_sub, and Z_sub respectively.
> 
> I'd love to write methods which speicialize on pairs
> of these classes. It works in lisp as follows
> 
> (defmethod mymethod (( x X) ( y Y)) ;; # 1
>   ...)
> 
> (defmethod mymethod (( x X_sub) ( y Y)) ;; # 2
>   ...)
> 
> (defmethod mymethod (( z Z) ( x X)) ;; # 3
>   ..)
> 
> 
> Then for example if i call mymethod with
> an instance of X_sub and Y_sub then # 2
> gets called.
> 
> These multi-methods are extremely useful to the
> lisp programmer.
> 
> How do python programmers work around this limitation?
> 
> One option would be to force all methods to have
> a huge case statement inside them which tests
> the  class of the second argument. And everytime a new
> class is added, all the case statements have to be
> revisited and updated accordingly?
> 
> Is there a better way?  perhaps there is a standard
> mult-method-dispatch package available for use?
> 
> -jim
> 




More information about the Python-list mailing list