[Python-3000] Adaptation [was:Re: Iterators for dict keys, values, and items == annoying :)]

Alex Martelli aleaxit at gmail.com
Sat Apr 1 07:20:37 CEST 2006


On Mar 31, 2006, at 3:47 PM, Jim Jewett wrote:

> On 3/30/06, Alex Martelli <aleaxit at gmail.com> wrote:
>> Consider __index__, and a user of gmpy, assuming
>> gmpy didn't rush out a 2.5 release with tp_index support.
>> The user of gmpy would be stuck -- no way he could
>> use a gmpy.mpz as an index into a list, because
>> the ad-hoc-adaptation of __index__ means that the type
>> itself must grow the slot.
>
> So the adaptation would be
>
>     def gmpy_mpz_index(self):
>         return long(self)
>     gmpy.mpz.__index__=gmpy_mpz_index
>
> Monkeypatching someone else's class may not be pretty, but adaptation

And may just be impossible for ``classes'' that are actually types  
implemented in C, as is the case for gmpy.

> is basically a standing offer to (less efficiently) pretend you did.
> If neither the caller nor the callee makes an explicit call to the
> adaption machinery, then you might as well change the original class.
>
> At the moment, some classes throw an TypeError if you try to add
> attributes later.  Are you suggesting that this behavior should be
> removed?  (I'll grant that it isn't *usually* helpful.)

I doubt the advantage's worth breaking compatibility with all  
existing C-coded extensions.

And the existing way to simulate adaptation isn't most typically to  
add special methods to an existing class (though, experimentally,  
gmpy may do it to decimal.Decimal, in the current release) --  
probably because in the current implementation that just wouldn't  
work with types (implemented in C).  Rather, look (e.g.) at copy_reg  
for the typical kludge that's used to reimplement that crucial design  
pattern that is adaptation, over and over and over again.

> What about updates, rather than inserts?  Should I be able to replace
> dict.__getitem__ and have it affect all existing dicts?

If that's what you want, I suggest Ruby -- the fact that everything  
is always mutable is one big reason I'm wary of actually trying  
production-level development in Ruby (well, right now there's also  
the fact that Google uses Python, not Ruby, but that reason didn't  
apply to me until I moved to Google exactly a year ago;-).

Anyway, that tangent has nothing to do with adaptation.

>
> (And if this thread continues, should it move to python-dev?)

If it discusses making every type mutable, I think it should stay on  
python-3000.  As far as adaptation (which has nothing to do with that  
idea, really) is concerned, I have no problem moving the thread --  
just little hope that adaptation will actually make it into the  
language in any 2.* release (for no good reason).


Alex



More information about the Python-3000 mailing list