[Python-3000] Adaptation vs. Generic Functions

Walter Dörwald walter at livinglogic.de
Wed Apr 5 16:30:52 CEST 2006


Nick Coghlan wrote:

> [...]
>      def default_adapter(self, *args):
>          """Call result when no adapter was found"""
>          raise TypeError("Can't adapt %s to %s" %
>                          (args[0].__class__.__name__, self.name))

+1 This makes it easy to add fallbacks:

class XReprProtocol(Protocol):
   def default_adapter(self, *args):
      return repr(*args)

xrepr = XReprProtocol("xrepr")

@XReprProtocol.register_for(list)
def xrepr_list(obj):
   return "[%s]" % ", ".join(xrepr(x) for x in obj)

@XReprProtocol.register_for(tuple)
def xrepr_tuple(obj):
   return "(%s)" % ", ".join(xrepr(x) for x in obj)

@XReprProtocol.register_for(int, long)
def xrepr_number(obj):
   return hex(obj)

For all other objects it falls back to the normal repr().

>      def __call__(self, *args):
>          """Adapt supplied arguments to this protocol"""
>          for key in self.candidate_keys(args):
>              try:
>                  adapter = self.registry[key]
>              except KeyError:
>                  pass
>              else:
>                  return adapter(*args)
>          return self.default_adapter(*args)

It would be great if __call__() would pass on keywords arguments to the
adapter too. (This would probably mean that candidate_keys would need
*args, **kwargs arguments). But then calling the adapter is totally generic.

Servus,
   Walter


More information about the Python-3000 mailing list