[Python-3000] Generic functions

Walter Dörwald walter at livinglogic.de
Tue Apr 4 10:20:10 CEST 2006


Ian Bicking wrote:

> Guido van Rossum wrote:
> 
>[...] 
>> What does when(object=list) mean? Does it do an isinstance() check?
> 
> Yes; I think RuleDispatch has a form (though I can't remember what the 
> form is -- it isn't .when()).

What happens, if I do the following

@PrettyPrinter.pformat.when(object=list)
def foo(...):
    ...

@PrettyPrinter.pformat.when(object=object)
def foo(...):
    ...

How does it know which isinstance() check to do first?

And what happens with performance if I have registered many handler 
functions?

> [...] 
> 
> The implementation of my simplistic form of generic function isn't too 
> hard.  Ignoring keyword arguments, it might work like:
> 
> class generic(object):
>      def __init__(self, func):
>          self.func = func
>          self.registry = {}
>      def __call__(self, *args):
>          for pattern, implementation in self.registry.items():
>              for passed, expected in zip(args, pattern):
>                  # None is a wildcard here:
>                  if (expected is not None and
>                      not isinstance(passed, expected)):
>                      break
>              else:
>                  return implementation(*args)
>          return self.func(*args)
>      def when(self, *args):
>          def decorator(func):
>              self.registry[args] = func
>              return func
>          return decorator
>      def __get__(self, obj, type=None):
>          if obj is None:
>              return self
>          return types.MethodType(self, obj, type)
> 
> There's lots of details, and handling keyword arguments, dealing 
> intelligently with subclasses, and other things I probably haven't 
> thought of.  But anyway, this allows:
> 
> class PrettyPrinter:
>      def pformat(self, object): ...
> 
> # Without keyword arguments I have to give a wildcard for the self
> # argument...
> @PrettyPrinter.pformat(None, list)
> def pformat_list(self, object):
>      ...

I don't understand! There's no generic in sight here!

Bye,
    Walter Dörwald


More information about the Python-3000 mailing list