Noob Q: subclassing or wrapping file class

Terry Reedy tjreedy at
Thu Sep 17 03:09:12 CEST 2009

kj wrote:
> I'm trying to get the hang of Python's OO model, so I set up this
> conceptually simple problem of creating a new file-like class to
> read a certain type of file.  The data in this type of file consists
> of multiline "chunks" separated by lines consisting of a single
> ".".
> My first crack at it looks like this:
> class MyFile():
>     def __init__(self, f):
>         if hasattr(f, 'next'):
>             self.fh = f
>         else:
>             self.fh = file(f, 'r')

I believe open(f, 'r') does the same thing. In 3.x, 'file' is gone and 
you must use 'open', so you might want to start using it now.

>     def __iter__(self):
>         return self
>     def next(self):
>         buf = []
>         for line in self.fh:
>             if line == '.\n':
>                 break
>             buf.append(line)
>         if len(buf) == 0:
>             raise StopIteration
>         return buf

FYI, what you have written to this point is an iterator class that could 
be rewritten as a generator function. You might fine that an instructive 

Terry Jan Reedy

More information about the Python-list mailing list