PartialInterfaces ? Re: Checking the type
Clark C. Evans
cce at clarkevans.com
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=a
> except IndexError: pass # empty alist's OK
> # and finally operate -- no exceptions expected
> alist = alist
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)
def __init__(self, append=0,extend=0,index=0,...
if self.check_append: append = alist.append
if self.check_extend: extend = alist.extend
try: alist = alist
except IndexError: pass
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!
More information about the Python-list