File-like filter pattern?

Erik Max Francis max at alcyone.com
Tue Dec 17 20:55:37 EST 2002


Is there a commonly accepted pattern for implementing file-like filters
in Python?  That is, a generally accepted approach for file-like objects
that can act as filters and point to other file-like objects (which may
themselves also be filters).

For EmPy (my Python templating system), I support filtering of processed
text, and to do this I have a base filter class which looks like this
(I've trimmed some bells and whistles out, as well as some
implementation details):

class Filter:

    """An abstract filter."""

    def __init__(self):
        if self.__class__ is Filter:
            raise NotImplementedError
        self.sink = None

    def write(self, data):
        raise NotImplementedError

    def writelines(self, lines):
        for line in lines:
            self.write(line)

    def flush(self):
        self.sink.flush()

    def close(self):
        self.flush()
        self.sink.close()

In this case, the sink attribute is the next filter in the line, which
may itself be a filter.  The choice of sink as the crucial attribute, of
course, was arbitrary.  The point is, multiple filters can be chained
together, so long as the end of the chain results in some meaningful
file-like object (which of course need not be an actual file; it could
be a StringIO or anything else meaningful).

My question is:  Is there a more accepted standard that it would be
better to follow?  This obviously works, and there's nothing wrong with
it, but if there's some more accepted/recognized way of doing it I'd
prefer to use that instead.  (I checked Google Groups and the Cookbook
and didn't find anything obvious.)

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ The gates of Heaven are open wide / Off I ride ...
\__/ Ch'u Tz'u
    Bosskey.net: Counter-Strike / http://www.bosskey.net/cs/
 A personal guide to Counter-Strike.



More information about the Python-list mailing list