File-like filter pattern?

Erik Max Francis max at alcyone.com
Wed Dec 18 05:41:23 EST 2002


"Martin v. Löwis" wrote:
> 
> Erik Max Francis <max at alcyone.com> writes:
> 
> > Is there a commonly accepted pattern for implementing file-like
> > filters
> > in Python?
> 
> Codecs work this way, see codecs.StreamReader and codecs.StreamWriter.

In my case I dissented from the obvious choice of having the appropriate
file-like object that the filter connects to (gzip.GzipFile is another
obvious example) in the constructor, since I wanted people to be able to
create a bunch of filters (of varying types, of course), and them stream
them all together, rather than being mandated to created them in reverse
order, so to speak.  This is how the current implementation of EmPy
handles streams (you can chain them together manually or let EmPy do it
for you by passing a list).  At present you attach a filter to a next
one in the sequence by calling firstFilter.attach(secondFilter), but,
again, you can just pass a list of filters to the appropriate function,
and provided they're derived from the given Filter class, all the hard
work is done for you (the filters are attached to the next in order
until the last, which is attached to the proxy stdout).

So maybe I should just abstract back one step, and have the base
("abstract") Filter class implement those methods, and then have the
basic implementations that are included with EmPy simply use sink as
their implementation detail.  Does that sound more reasonable than
asserting that people use a sink attribute?  In a way, it's a painless
transition, since you just need to offer a next method (that returns
what's next in line or None).  Call it a holdover from my non-Python
days, but I tend to prefer interfaces defined in terms of methods,
rather than attributes.

So in the new formulation, a filter is an object that implements a
file-like interface (minimally:  write, flush, and close methods), and
implements methods for hooking them up to another file-like object
(filter or not) via attach, and possibly detach, with the obvious choice
of a next method which would indicate what is actually next in line (or
None).  Does this sound like a better design than the previous one,
which is file-like interface, and then a sink attribute (not method),
supplemented by an attach method (which simply sets the sink attribute)?
What sounds more Pythonic?

Thoughts?

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Bring me men / Bring me men to match my mountains
\__/ Lamya
    Church / http://www.alcyone.com/pyos/church/
 A lambda calculus explorer in Python.



More information about the Python-list mailing list