Python's idiom for function overloads

John Hunter jdhunter at ace.bsd.uchicago.edu
Mon Jan 31 23:14:11 EST 2005


>>>>> "Frans" == Frans Englich <frans.englich at telia.com> writes:

    Frans> Hello,

    Frans> Since Python doesn't have static typing, how is the same
    Frans> result as traditional function overloads results in
    Frans> acheived? With function overloads the "selection of code
    Frans> path depending on data type" is transparent and automatic
    Frans> since the typing system figure out what goes to what.

    Frans> But in Python, when one wants to be able to pass different
    Frans> data types into a single "entry point" for functionality,
    Frans> how is that best done? To in a function do an if statement
    Frans> with the type() function?

Using type or isinstance is one way to do it.  The other way is "duck
typing".  If it walks like a duck and talks like a duck, it probably
is a duck.  The core idea is that we care less about what type an
object is, and more about what services the object provides.  Eg

def myoverload(x):

  try: noise = x.quack()
  except AttributeError: # do something else...
  else: # do something with noise

Variants to the try/except approach include hasattr, getattr and so
on..

googling python duck typing should speed you on your way.

JDH




More information about the Python-list mailing list