I'm using an API that expects me to pass in a file object for reading, but I want to pass in just a portion of an existing file so that the API reads just the first n bytes. I assume I could wrap 'file' in my own class, something like:
class FilePortion(file):
def __init__(self, name, mode, lastByteToRead):
self.LAST_BYTE = lastByteToRead
super(FilePortion, self).__init__(name, mode)
def read(self, size=None):
position = self.tell()
if position < self.LAST_BYTE:
readSize = self.LAST_BYTE - position
if size and size < readSize:
readSize = size
return super(FilePortion, self).read(readSize)
else:
return ''
...except I'm not sure what other methods to override and how exactly. How would I override next(), for example? Is there a better way of doing this?