[Python-Dev] type categories

Guido van Rossum guido@python.org
Wed, 14 Aug 2002 22:24:07 -0400


> Greg> Would all the versions of f have to be written together like
> Greg> that?
> 
> I'm not sure.  In ML, they do, but in ML, the tests are on
> values, not types (ML has neither inheritance nor overloading).
> Obviously, it would be nice not to have to write the versions
> of f together, but I haven't thought about how such a feature
> would be defined or implemented.
> 
> Greg> I think when most people talk of multiple
> Greg> dispatch they have something more flexible in mind.
> 
> Probably true.

I can see how it could be done using some additional syntax similar to
what ML uses, e.g.:

  def f(a: Cat1):
      ...code for Cat1...
  else f(a: Cat2):
      ...code for Cat2...
  else f(a: Cat3):
      ...code for Cat3...

Don't take this syntax too seriously!  I just mean that there is a
single statement that provides the different alternative versions.

Another approach would be more in the spirit of properties in 2.2:

  def f1(a: Cat1):
    ...code for Cat1...

  def f2(a: Cat2):
    ...code for Cat2...

  def f3(a: Cat3):
    ...code for Cat3...

  f = multimethod(f1, f2, f3)

(There could be a way to spell this without having the type
declaration syntax in the argument list, and do it in the
multimethod() call instead, e.g. with keyword arguments or passing a
list of tuples: [(f1, Cat1), (f2, Cat2), ...].  I suppose this could
be extended to more arguments as well.)

It might also be possible to modify a multimethod dynamically,
e.g. later one could write:

  def f4(a: Cat4):
    ...code for Cat4...

  f.add(f4)

This is more in the spirit of Python than your original proposal,
which appeared like the compiler would have to gather all the
definitions from different places and fuse them.  That would be too
complex for Python's simple-minded compiler!

--Guido van Rossum (home page: http://www.python.org/~guido/)