Replacing overloaded functions with closures.

Terry Reedy tjreedy at udel.edu
Mon Jul 30 13:05:14 EDT 2007


"king kikapu" <aboudouvas at panafonet.gr> wrote in message 
news:1185810128.237758.17550 at k79g2000hse.googlegroups.com...
| > 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))
|
| I have already come up with that solution but
|...And get rid of the isinstance commands.

A sometimes alternative is a dict (untested):

func_switch = {
  bool: lambda o: not o,
  int: lambda i: i*2,
  str: lambda s: s+s,
  unicode: lambda s: s+s
}

def func(o):
  try: return func_switch[type(o)]
  except IndexError:
     raise NotImplementedError('type %r not supported' % type(obj))

but this does not work for instances of subclasses the way isinstance does.

tjr







More information about the Python-list mailing list