PartialInterfaces ? Re: Checking the type
aleaxit at yahoo.com
Fri Mar 23 13:40:44 CET 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
> 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_index =index
> def check(self,alist)
> if self.check_append: append = alist.append
> if self.check_extend: extend = alist.extend
> if self.check_index:
> try: alist = alist
> except IndexError: pass
> return alist
> except AttributeError
> return None
> What do you think? Kinda slow, hunh?
Rather. Maybe slightly better:
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=alist), though I guess that
could be added as a special case (maybe in a derived
class of checker_of_methods specialized for sequence
Anyway, usage here might be, e.g.:
append, extend = checker_of_methods(
More information about the Python-list