PartialInterfaces ? Re: Checking the type

Clark C. Evans cce at
Fri Mar 23 11:43:11 CET 2001

> # safer
> def munge(alist):
>     # first extract all bound-methods we'll need
>     append = alist.append
>     extend = alist.extend
>     # then check operations such as indexing
>     try: a[0]=a[0]
>     except IndexError: pass    # empty alist's OK
>     # and finally operate -- no exceptions expected
>     append(23)
>     extend(range(5))
>     append(42)
>     alist[4] = alist[3]
>     extend(range(2))

This is a very cool, "protocol", a partial interface.
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[0] = alist[0]
                 except IndexError: pass
              return alist
          except AttributeError
             return None

What do you think?  Kinda slow, hunh?

> This doesn't interfere with polymorphism (any
> object supporting all needed operations with the
> right semantics will do), and yet is safer than
> the previous version _without_ being substantially
> slower or more complicated (well, a little, I guess).
> It's important to avoid overdoing the checks, but
> the assert statement can come in handy for checks
> we don't want to happen in production/optimized
> code (e.g, one may add "assert callable(append)"
> etc to the above example).
> (Such versions of the look-before-you-leap idiom
> is popular in C++ templates, to get compiler
> errors that are clearer and earlier, but then,
> I've often said that C++ templates and Python
> functions show surprising parallels:-).

Yes, this was neat!

;) Clark

More information about the Python-list mailing list