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

Benji York benji at benjiyork.com
Sat Apr 1 16:35:23 CEST 2006


Alex Martelli <aleaxit at gmail.com> wrote:
> Consider __index__, and a user of gmpy,

Jim Jewett wrote:
> 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
> is basically a standing offer to (less efficiently) pretend you did. 

No, monkey patching isn't pretty, thankfully that's not how it works. 
To express that use case with Zope 3 adaptation you'd want an IIndex 
interface that (say) promises to have a .index() method, if you want to 
get an index from a gmpy value, you'd adapt it like so, and call the 
method:

IIndex(gmpy_value).index()

It's a design decision as to weather a particular method wants just an 
index passed in, wants something that already conforms to the IIndex 
interface (which is really duck typing, in Z3 we don't enforce 
interfaces), or something that is adaptable to IInterface.

So, if I wanted to use gmpy.mpz objects as indices and there isn't an 
appropriate adapter, I can define my own.  If the gmpy project then 
added an .index() method to mpz objects and flagged them as providing 
IIndex, my adapter wouldn't be necessary any more (because adapting 
something to an interface that it already provides returns the original 
object).  Alternately they could provide their own adapter, and I could 
stop using mine.
--
Benji York


More information about the Python-3000 mailing list