Replacing overloaded functions with closures.

Neil Cerutti horpner at yahoo.com
Mon Jul 30 11:27:32 EDT 2007


On 2007-07-30, king kikapu <aboudouvas at panafonet.gr> wrote:
> i am trying, to no avail yet, to take a C#'s overloaded
> functions skeleton and rewrite it in Python by using closures.
> I read somewhere on the net
> (http://dirtsimple.org/2004/12/python-is- not-java.html) that
> in Python we can reduce code duplication for overloaded
> functions by using closures.
>
> I do not quite understand this. Let's say we have the following
> simple C# code:
>
> int func(int i) { return i * 2; }
> string func(string s) { return s + s; }
> bool func(bool f) { return !f; }
>
> I wasn't able to find a way to express this thing in closures.

The closures discussed in the article are not a solution for
function overloading. They are a solution for function
composition.

Python generally has no need for function name overloading--if
you really want it you must do it manually using runtime type
checking.

def func(obj):
  if isinstance(obj, bool):
    return not obj
  elif isinstance(obj, int):
    return obj * 2
  elif isinstance(obj, basestring):
    return obj + obj
  else:
    raise NotImplementedError('type %r not supported' % type(obj))

The article you linked, when discussing Python closures is really
just advocating the use of higher-order functions. But Java's
verbosity and lack of free functions are the only irritating
obstacle to using them just as you would in Python. I'm not sure
what the author was getting at, exactly.

-- 
Neil Cerutti



More information about the Python-list mailing list