title: Efficient way to generate content for a "fake" file-like object in python
body: <p>In test code, I pass an instance of the below file-like object to a function which normally expects a file. The function uploads the contents, using a series of 8KB read()s.</p>
  
  <p>It works fine, simulates the contents of a file with consistent but changing data ("0123456789abcdef0123..."). </p>
  
  <p>Problem is that it is slow and appears to use a lot of memory -- it gets killed by an OOM killer. I guess the 8K strings returned by read() are not gc'd fast enough?</p>
  
  <p>Anyway, I'd rather not increase memory requirements for this test or use a fixed-size pre-allocated string. </p>
  
  <p>Found an old article <a href="https://waymoot.org/home/python_string/" rel="nofollow noreferrer">https://waymoot.org/home/python_string/</a> which indicates this is the best approach, but please share any ideas about how to do this more efficiently.</p>
  
  <pre><code>class FakeFile():
      '''A file-like object that generates a fixed byte stream, so that uploads
      can be verified without having a large file on disk.'''
      def __init__(self, length = 10 * 1024 * 1024): # 10 megabytes
          self.idx = 0
          self.length = length
      def read(self, size=None):
          r = ''
          max = self.length - self.idx
          if size == None or size &gt; max:
              size = max
          r = "".join(['%x' % (c%16) for c in range(self.idx, self.idx+size)])
          self.idx += size
          return r
      def readLine(self, size=None): # - read one entire line from the file.
          return self.read()
      def close(): # - close the file.
          pass
      def seek(self, i, dir):
          import os
          if dir==os.SEEK_CUR:
              self.idx += i
          elif dir==os.SEEK_SET:
              self.idx = i
          elif dir==os.SEEK_END:
              self.idx = self.length - i
          else:
              raise ValueError()
  </code></pre>