Multimethods 101 (was Re: Multiple dispatch (Re: Q: Python 2.0 preliminary features?))

Louis Madon madonl at bigfoot.com
Sat Oct 30 07:01:03 EDT 1999


Bruce Hoult wrote:
> 
 > > For example, you suggested that maybe something in module X calls
> > > something in module Y, passing it a BB.  Module Y creates an AA (which X
> > > doesn't know about) and calls foo(AA, BB).  oops.  The only place that
> > > this problem can be detected at compile-time is in module X, and then only
> > > if the compiler knows that module Y imports both AA and foo EVEN IF IT
> > > DOESN'T RE-EXPORT THEM.  This seems like a big ask.
> >
> > I agree, but isn't that what runtime exceptions are for?
> 
> That's right, but some people seem to prefer to get told about potential
> problems at compile time -- there is always a danger that the particular
> case that causes the exception doesn't get exercised in testing but gets
> hit in the field.

Guaranteed compile time errors on this would certainly be nice.  [BTW, I
wonder what Cecil does here?  Its statically typed and the compiler does
whole-program analysis, so perhaps it *can* report this kind of error at
compile time?].

> 
> > >  If not then perhaps foo() is trying to do too much and
> > > should be split up?  In particular, perhaps there should instead be a
> > > bar(A) and baz(B) and just a single, generic, version of foo(A, B) that
> > > calls bar(A) and baz(B) as part of its operation.  In which case the
> > > implementator of AA should make a bar(AA) and the implementatior of BB
> > > should make a baz(BB). And then all is sweetness and light :-)
> >
> > You're not suggesting explicit type tests inside foo(A, B) are you?
> 
> Aww, *maate*.  Strewth, I'm not suggesting any such thing as a type test.

Sorry, I didn't read your point properly.

> 
> > Thats precisely the kind of thing we need to get away from.  I could
> > come along and define a new class AB that inherits from both A and B and
> > all of a sudden your typecase is broken.
> 
> The only typecase is in the (compiler-generated) code for the generic
> function itself.
> 
> When you define your class AB, you'll just need to define appropriate
> bar(AB) and baz(AB) methods.

So if the function that foo performs allows independant processing of
each argument, then yes I agree.  I think the more interesting case is
where you can't easily split it up like that :- 

eg. foo = 'add', 
	A = datetime, AA = limited-datetime{minDate, maxDate}, 
	B = time-offset, BB = time-offset-with-weekday-adjustment. 

[So when you add a BB to a datetime it automatically increases the
offset by whatever amount neccesary to make sure the resulting datetime
falls on the next closest weekday].

Louis.




More information about the Python-list mailing list