title: Should I close a stream (file-like object) passed into my object in the context manager __exit__() function?
body: <p>I have an object which I'd like to be able to use the <code>with</code> keyword on. I'm happy with the practicalities implementing context managers but I'm hitting my head up against a best practice kind of issue.</p>
  
  <p>The object is a wrapper around a file. I'm planning for my object to be initialised either with a string (the path of the file) or with a file-like which can be dealt with directly (there's a possibility of files inside files - so I foresee a definite use case for this with BytesIO etc...)</p>
  
  <p>So <code>__init__</code>looks something like this:</p>
  
  <pre><code>def __init__(self, file_to_process):
      if isinstance(file_to_process, str):
          self._underlying_stream = open(file_to_process, "rb") # it's the path to a file
      elif isinstance(file_to_process, io.IOBase):
          self._underlying_stream = file_to_process # its the file itself
      else:
           raise TypeError()
  </code></pre>
  
  <p>So my question is, is it best practice/acceptable/sensible to close that <code>_underlying_stream</code> in my <code>__exit__()</code> function? It totally makes sense when it was a path, but if it's a stream passed in, it strikes me as impolite at best and dangerous at worst to close <code>self._underlying_stream</code> - <strong>am I correct to be thinking that, and if so, is there a neat way around this?</strong></p>
  
  <p>(Note: I considered wrapping the stream coming in with a <code>io.BufferedReader</code>, but it turns out that closing that will also close the underlying stream...)</p>