## Multimethods for Python

From: andrew cooke <andrew@...>

Date: Thu, 5 May 2011 17:44:53 -0300

Within pytyp (still in progress) I have a need to call two different
functions, depending on the type of a certain argument.  Typically in OOP you
make this a method and dispatch on the instance type.  But in this case
subclassing isn't so easy.

So, instead, you need to write an explicit test for the type, and then call
the right function yourself.

Or... perhaps you could use a multimethod:

class Verify:

@multimethod
def __call__(self, spec:Product, svn, check=isinstance):
try:
for (v, s, _) in vsn:
if not check(v, s):
return False
return True
except TypeError:
return False

@multimethod
def __call__(self, spec:Sum, svn, check=isinstance):
try:
for (v, s, _) in vsn:
try:
if check(v, s):
return True
except TypeError:
pass
except TypeError:
pass
return False

That doesn't exist yet, but I see no reason why it can't be made to work.  In
case it's not blindingly obvious, when you call __call__() above, which method
is actually called will depend on the type of the "spec" argument.

(I am hoping that the syntax above will work; it's going to require a little
magic with locals() I suspect.  We'll see...)

Andrew