PartialInterfaces ? Re: Checking the type
Alex Martelli
aleaxit at yahoo.com
Fri Mar 23 07:40:44 EST 2001
"Clark C. Evans" <cce at clarkevans.com> wrote in message
news:mailman.985343914.18681.python-list at python.org...
> > # safer
> > def munge(alist):
> > # first extract all bound-methods we'll need
> > append = alist.append
> > extend = alist.extend
[snip]
> This is a very cool, "protocol", a partial interface.
Why, thanks. Wish I could claim originality:-), but,
as I said, this (or a close analog thereof) is rather
standard fare in C++ templates.
> I was thinking about how this could be formalized as
> a "checker/adapter"... here is very imperfect code)
>
> class partial_list_checker:
> def __init__(self, append=0,extend=0,index=0,...
> self.check_append=append
> self.check_extend=extend
> self.check_index =index
> ...
>
> def check(self,alist)
> try:
> if self.check_append: append = alist.append
> if self.check_extend: extend = alist.extend
> if self.check_index:
> try: alist[0] = alist[0]
> except IndexError: pass
> ...
> return alist
> except AttributeError
> return None
>
> What do you think? Kinda slow, hunh?
Rather. Maybe slightly better:
class checker_of_methods:
def __init__(self, *method_names_needed):
self.method_names_needed = method_names_needed
def check(self, anobj):
return [ getattr(anobj, method)
for method in self.method_names_needed ]
I'd let the AttributeError propagate up to the caller
of achecker.check if the object being checked does not
supply a needed method -- seems simples/smoothest. And
I think returning the already-bound methods is also a
(very slight) optimization as well as a simplification.
Of course, this doesn't handle the specific check for
indexability (alist[0]=alist[0]), though I guess that
could be added as a special case (maybe in a derived
class of checker_of_methods specialized for sequence
checking).
Anyway, usage here might be, e.g.:
append, extend = checker_of_methods(
'append', 'extend').check(alist)
Alex
More information about the Python-list
mailing list