Function Overloading Without Typechecking

Alex Martelli aleax at aleax.it
Tue Jan 15 15:29:01 EST 2002


Michael Chermside wrote:
        ...
> Well, that's fine, but I have gotten used to having method overloading
> in Java and C++. So I like to write things like this:
> 
>      def spamThemAll(stuffToSpam):
>          if type(stuffToSpam) in types.StringTypes:
>              stuffToSpam = stuffToSpam.split()
        ...
> So what do I do? I can think of a few possibilities:
        ...
> How do those of you who are more experienced with this handle this issue?

def spamThemAll(stuffToSpam):
    # split if splittable
    try: stuffToSpam = stuffToSpam.split()
    except AttributeError: pass
    # etc

General approach: decide what it means in context for an object x to "be
a string".  In this specific context, it seems to mean "have a .split() 
method", so just try to use that method as you think it should be usable,
and use a try/except to handle the possibility that no such method is
in fact there.  Situations of this kind make up a majority of cases. 

Another case, rarer but by no means rare, is something like the need to 
treat a string as 'atomic' (a "scalar") as opposed to lists, tuples, and 
other "true" sequences (while in Python itself, a string is a sequence).  

For that need I generally synthesize a simple test:

        try: mysteryObject+''
        except TypeError:
            try: for x in mysteryObject: break
            except TypeError: isSequence = 0
            else: isSequence = 1
        else: isSequence = 0 # string-like object -> non-sequence

Similarly, I might 'test for Numeric' by similarly trying a + 0, etc.


Rarest, but still interesting (I did hit upon it once or twice) is the case 
I address in a Cookbook recipe, 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52291

I guess it was a bit silly of me to touch only upon the rarest of cases
of "type-checking" needs rather than directly address the typical 
interesting cases best covered by "easier to get forgiveness than
permission" (try/except) rather than "look before you leap" (type
testing) -- but I was keen to show that even when it _seems_ type
checking is the only alternative, it still _isn't_ (...mostly...).  And, the
need I cover in the recipe had in fact come up recently for me when
I posted it -- sometimes unusual occurrences are closer to our
attention just because of their unusual nature.

Still, there are plenty of examples of "egfp" and its preferability
to "lbyl" in the Cookbook, albeit not as sharp as recipe 52291:-).


Alex




More information about the Python-list mailing list