generic functions in python

Jim Newton jimka at rdrop.com
Sat May 29 06:25:42 EDT 2004


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