Function Overloading Without Typechecking

Michael Chermside mcherm at destiny.com
Tue Jan 15 18:37:39 CET 2002


I have to confess... I come to Python from the world of static typing, 
and am still adjusting my mindset to dynamic typing. But I'm interested 
in learning how to use Python's dynamic typing (as opposed to weak 
typing) effectively. Frequent comments from Alex Martelli and others 
suggest that if I really want to write pythonic-ly, I will try NOT to 
check the types of the values I am passed. Just use it, and unless the 
caller passed me the wrong kind of thing, it'll work.

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()
         for s in stuffToSpam:
             spam(s)

That way I can invoke the method with two different kinds of values:

     spamThemAll( ['a', 'b', 'c'] )
     spamThemAll( 'a b c' )

... and it automatically converts. Convenient, but dangerous. For 
instance, if I had used "type(stuffToSpam) == types.String" as my test, 
then it wouldn't have worked for unicode strings. And this version will 
probably break on some other type which I haven't prepared for (UserString).

So what do I do? I can think of a few possibilities:

    1) Just don't do it. Only accept one type and make the caller
       convert.

       [But this is awkward for the caller!]

    2) Use optional keyword arguments:
          def spamThemAll( str=None, seq=None ):
              if str is not None:
                  seq = str.split()
              for s in seq:
                  spam(s)

        [But this makes the caller use keyword args always!]

    3) Create multiple methods:
           def spamThemAll_withString(str):
               return spamThemAll_withSeq( str.split() )

        [But this creates annoying extra functions!]

How do those of you who are more experienced with this handle this issue?

-- Michael Chermside






More information about the Python-list mailing list