Re: Easy "switch statements" and "function overloading" in python

Jim Roskind (jar@infoseek.com)
Sun, 3 Apr 1994 15:43:20 +0800

> Date: Sun, 3 Apr 1994 13:27:52 +0800
> From: jar@infoseek.com (Jim Roskind)
>
> [how to overload function calls based on "type()"]
> You should also note that instances of *all* user
> defined classes are "<type 'instance'>". As a result, if you want
> different overloading for each user defined class, you'd have to have
> one more dispatch level:
>
> def my_print_instance(val):
> return my_print_instance_func_table[val.__class__](val)

Before I get a lot of mail telling me that I *don't* need to overload
based on class-type (for user defined types) "'cause that is what
virtual functions are for," I should give a bit of motivation.

IF you are defining all the types of instances that will ever call a
given function, THEN you can call the appropriate function in those
classes and simply doing:

def my_print_instance(val):
return val.my_print_instance()

Indeed, this is the *preferred* approach to function dispatch selection
based on class-type.

Unfortunately, IF you don't have the luxury of defining the classes
that will come at you, then you can't get away with this Python based
function dispatch. The easy (almost) fix of:

def my_print_instance(val):
try:
mpi_func = val.my_print_instance
except AttributeError:
return my_print_instance_default(val)
return mpi_func()

doesn't quite work either. The problem is that you might be called
with an argument instance that happens to have a method called
"my_print_instance", but was *not* defined by you (i.e., has
completely different semantics). ...ooops. :-(

Anyhoooo... the only way to dispatch based on types, when you don't
have the luxury of adding methods to any instances of user defined
classes that "come at you," is (I think) to use some variant of the
technique I described. :-)

Jim

Jim Roskind
408-982-4469
jar@infoseek.com