Python's idiom for function overloads

F. GEIGER f.geiger at vol.at
Tue Feb 1 05:07:07 EST 2005


> > Since Python doesn't have static typing, how is the same result as
traditional
> > function overloads results in acheived?

The more you program in Python, the less you are missing it.

As Philippe already said, use objects that support the protocol or decide
what to do with it after having checked its type. I do that, if I have to,
like so:

def doIt(arg):
   if type(arg) == type([]):
      map(doIt, arg)
   else:
      # Do it on a scalar type
      # ...
      return result

HTH
Franz GEIGER


"Philippe Fremy" <phil at freehackers.org> schrieb im Newsbeitrag
news:41ff066c$0$6473$636a15ce at news.free.fr...
> Hi Frans,
>
> > Since Python doesn't have static typing, how is the same result as
traditional
> > function overloads results in acheived?
>
> With dynamic typing obviously. :-)
>
> You can not reproduce the C++ overload idiom but you can get something
> close with manual type testing.
>
>  > To in a
>  > function do an if statement with the type() function?
>
> I am not aware of any other method.
>
> def a( arg1 ):
> if type(arg1) == types.IntType: return aWithInt(arg1)
> if type(arg1) == types.ListType: return aWithList(arg1)
> ...
>
> As you see, it is a bit tedious sometimes.
>
> If you want to juggle with completely different signatures, you have to
> play with variable argument lists. But I have found in my experience
> that the best way to get close to the C++ idiom, while improving
> readbility, is by using kwparams:
>
> def a(**kwparams):
> if kwparams.has_key('argInt'): aWithInt(kwparams['argInt'])
> if kwparams.has_key('argString'): aWithString(kwparams['argString'])
>
> The parsing code is the same, but the intent of the user is better
> expressed and you can catch misuse in a better fashion:
> if kwparams.has_key('argInt') and kwparams.has_key('argString'):
> print "You stupid moron, a can be used only with string or int but not
> both at the same time!"
> sys.exit(1)
>
> The example speaks better in a real case. Imagine a processPixmap
function:
> processPixmap( pixmap=QPixmap(...) )
> processPixmap( filename='my_pixmap.png' )
> processPixmap( buffer=my_pixmap_string_content )
>
> It works actually even better with multiple arguments.
>
> regards,
>
> Philippe





More information about the Python-list mailing list