Negative block sizes with file-like objects

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Sep 27 03:02:27 EDT 2008


I have a proxy class that wraps an arbitrary file-like object fp and 
reads blocks of data from it. Is it safe to assume that fp.read(-1) will 
read until EOF? I know that's true for file.read() and StringIO.read(), 
but is it a reasonable assumption to make for arbitrary file-like objects?

To put it in more concrete terms, I have a class like this:

class C(object):
    # Much simplified version.
    def __init__(self, fp):
        self.fp = fp
    def read(self, size=-1):
        return self.fp.read(size)


Should I re-write the read() method like this?

    def read(self, size=-1):
        if size < 0:
            return self.fp.read()
        else:
            return self.fp.read(size)



-- 
Steven



More information about the Python-list mailing list