Function Overloading Without Typechecking

Emile van Sebille emile at fenx.com
Tue Jan 15 13:21:00 EST 2002


"Michael Chermside" <mcherm at destiny.com> wrote in message
news:mailman.1011116242.27626.python-list at python.org...
> 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' )
>

I look to make a function that will do the right thing for the
allowable args and then use it.  For your example, something
like:

>>> def tolist(arg):
 return filter(None, [a.strip() for a in list(arg)])

>>> tolist('a b c')
['a', 'b', 'c']
>>> tolist(['a','b','c'])
['a', 'b', 'c']



I sometimes run into situations where an obvious answer doesn't
come to mind, or when certain types don't play nice, and then I
revert to type checking as well.  ;-)


Emile van Sebille
emile at fenx.com

---------





More information about the Python-list mailing list