New-style classes (was Re: Checking for EOF in stream)

GiBo gibo at gentlemail.com
Mon Feb 19 20:30:59 EST 2007


GiBo wrote:
> Hi!
> 
> Classic situation - I have to process an input stream of unknown length
> until a I reach its end (EOF, End Of File). How do I check for EOF? 
> [...]
> I'd better like something like:
> 
> while not stream.eof():
> 	...

Is there a reason why some classes distributed with Python 2.5 are not
new-style classes? For instance StringIO is apparently "old-style" class
i.e. not inherited from "object". Can I somehow turn an existing
old-style class to a new-style one? I tried for example:
	class MyStreamIO(StreamIO, object):
		pass
but got an error. Is my only chance taking StringIO.py from python tree,
adding "(object)" to the class declaration and distributing it with my
source?

FWIW I created a wrapper class that does what I need with the EOF
problem in quite elegant way, but due to __getattribute__() stuff it
only works with new-style classes :-(

class MyStreamer(object):
        def __init__(self, stream):
                self._stream = stream
                self.eof = False

        def read(self, amount = None):
                data = self._stream.read(amount)
                if len(data) == 0:
                        self.eof = True
                        raise EOFError
                return data

        def __getattribute__(self, attribute):
                try:
                        return object.__getattribute__(self, attribute)
                except AttributeError:
                        pass
                return self._stream.__getattribute__(attribute)


GiBo





More information about the Python-list mailing list