[Python-3000] Adaptation vs. Generic Functions

Tim Hochberg tim.hochberg at cox.net
Wed Apr 5 23:39:35 CEST 2006

Guido van Rossum wrote:

>On 4/5/06, Tim Hochberg <tim.hochberg at cox.net> wrote:
>>Walter Dörwald wrote:
>>>What's still missing IMHO is a way for an adapter to defer to the next
>>>adapter in the chain, i.e. something like:
>>The concept seems good, but I find the implementation baffling, OK, I
>>finally figured it out. It only seems to work once though -- you can't
>>chain super calls. Why not simply raise a DeferToNextAdapter exception?
>I haven't used adapters in years, and I don't recall seeing this in
>Alex's recent posts; can either of you explain slowly what the use
>case is and how it's typically used? The code fragments shown so far
>aren't helping. :-(
I'm hoping that Walter can give some more realistic examples since I 
don't have real-world experience here. The basic idea is simply to let 
an adapter give up and let the protocol try the next adapter. This could 
happen in a generic function, for instance, if you wanted to try some 
fast algorithm for some specific subtypes, but the algorithm might be 
inappropriate depending on the values of the subtypes. You don't find 
that out till your in the adapter itself.  Consider:

def power(a, b):
    """return a**b"""
    return a**b
@power.register_for((int, int), (float, int), (complex, int))
def intpower(a, b):
    "Compute a**b quickly for some integral cases. Punt otherwise."
    if b == 0:
        return 1
    elif b == 1:
        return a
    elif b == 2:
        return a*a
        raise DeferToNextAdapter

This uses Nick Coghlan's GenericFunction implementation from a few posts 
ago with the DeferToNextAdapter stuff added. The example is contrived 
since I would really just call a**b directly in the else clause. 
However, I can see how in a case with more complicated / powerful type 
dispatching you might not know in advance what the next adapter was 
going to do, as you do here, so you'd want to hand responsibility back 
off to the GenericFunction instance.

I'll give this some more thought and see if I can come up with 
non-contrived examples.



More information about the Python-3000 mailing list