[Python-3000] Adaption & generic functions [was Generic functions]

Walter Dörwald walter at livinglogic.de
Fri Apr 7 20:43:48 CEST 2006


Jim Jewett wrote:

> On 4/5/06, Walter Dörwald <walter at livinglogic.de> wrote:
> 
>> class Sequence(Interface):
>>     def getitem(self, index): pass
>>     def len(self): pass
> 
>> class PythonSeqAsSequence(Sequence):
>>     def __init__(self, obj):
>>        self.obj = obj
> 
>>     def getitem(self, index):
>>        return self.obj[i]
> 
>>     def len(self):
>>        return len(self.obj)
> 
>> Sequence.register(PythonSeqAsSequence, list)
> 
> 
>> But if adapting is done via __call__() we have a problem: Sequence
>> already provides a __call__, the constructor.
> 
> So?  I can't see any reason why you would want to construct an
> (abstract) Sequence.  What would it mean?

The official adaption/overloading API might specify that an adapter must
be a callable object that has a register method, which can be used as a
decorator. If adaption is done to a single method protocol, calling the
protocol should return the result of calling the adapter, but if
adaption is done to a protocol with several methods, calling the
protocol returns an object that has those methods. Now if we want the
Interface declaration to be the protocol, this means that we call the
Interface class to get an object that provides this interface for the
object passed in.

> What you might want to do is to construct a specific Sequence, such as
> Sequence([1,2,3]), or the empty Sequence() .
> 
> Just as the list() constructor takes arguments and returns something
> that looks like a list, the Sequence() constructor should take an
> argument and return something that looks like a sequence.

You use the int() protocol to get an int from a string:
int("42"), the same way as you use the Sequence() protocol to get a
Sequence. (And if you're passing a long string, (i.e. int(100*"42")) you
don't even get an int.

> The difference from a "regular" class constructor is that you are less
> likely to create a new object if it can be done more efficiently, and
> there is no expectation that Sequence will appear in the object's mro.
> 
> Actually calling the sole method of an interface is admittedly more debatable.

Servus,
   Walter


More information about the Python-3000 mailing list