[Tutor] operators

Jeff Shannon jeff@ccvcorp.com
Fri Mar 28 14:56:02 2003


Isaac Hall wrote:

>So just to re_iterate, if I want a function (class method) to do 
>different things based on what is given to it, I need to check the type of 
>the objects within the fuction.  correct?
>

For some definition of "check the type of the objects" -- you don't 
necessarily need to use an explicit type() check.  Often, the best way 
to do "typechecking" is to simply try an operation, and if that fails 
then use a backup -- "It's easier to ask forgiveness than permission".

def itemcount(object):
    try:
        result = len(object)   # get the length of a sequence
    except TypeError:
        result = 1        # if it's not a sequence, then there's only 
one object
    return result

This has the advantage that it will work for *any* sequence (or class) 
that supports len() -- including types that you know nothing about, and 
even types that haven't been written yet.  An explicit type() call will 
let you catch lists, tuples, and strings, but what about array.arrays? 
Or numeric arrays?  Or some other specialized sequence object that you 
haven't thought of?  Thus, by simply trying something and seeing if it 
works (and catching the exception if it doesn't), you're creating code 
that's much more polymorphic than straightforward typechecking allows.

Jeff Shannon
Technician/Programmer
Credit International