OT(Slightly): Thanks to Python.

Josiah Carlson jcarlson at nospam.uci.edu
Sat Mar 13 02:17:56 EST 2004


> def foo(a, b) for (type1, type2):
>     print "type 1 & 2"
> 
> def foo(a, b) for (type3, type4):
>     print "type 3 & 4"

While I don't like the syntax you give, I do agree that it can be 
useful.  I've gotten used to doing the below, but letting the system 
take care of polymorphism would be convenient.

def foo(a, b):
     if type(a) is type1 and type(b) is type2:
         print "type 1 & 2"
     elif type(a) is type3 and type(b) is type4:
         print "type 3 & 4"
     else:
         raise TypeError("Improper argument types passed: %s %s"\
                         %(type(a),type(b)))

Certainly the above can be streamlined with a wrapper function:

def foo1_2(a,b):
     print "type 1 & 2"

def foo3_4(a,b):
     print "type 3 & 4"

def foo(a,b):
     dct = {(type1, type2):foo1_2,
            (type3, type4):foo3_4}
     return dct[type(a), type(b)](a,b)

Which shows us that manual polymorphism is not that bad.

  - Josiah



More information about the Python-list mailing list