title: Interactive mode within "with" statements
body: <p><a href="https://docs.python.org/3/reference/datamodel.html#context-managers" rel="nofollow noreferrer">With statement context managers</a> are convenient for many purposes. However, they can be inconvenient in an interactive shell, because the entire <code>with</code> statement is executed as a whole block, e.g.:</p>
  <pre><code>with open('test.txt', 'r') as fin:
      print(fin.readline())  # The result does not immediately output to the console
      for i in range(10):  # I may want to choose the number depending on the previous line's output
                           # (or do something else entirely), but I cannot
          print(fin.readline())  # Or any other sort of processing
  </code></pre>
  <p>As shown, this may be a problem if, for example, I want to &quot;explore&quot; a file's content before deciding what to do with it. What I usually end up doing is either reading the entire file into a string before processing it, or use multiple <code>with</code> statements to open the file multiple times, but obviously both of those solutions have limitations (e.g. the file may be too large to read into the memory, or the context manager in question may not be a file at all).</p>
  <p>A more general solution would be to eschew the <code>with</code> statement and use <code>fin.close()</code> instead. However, some context manager classes I use may not provide a <code>close()</code> method in their public interface. Of course I could explicitly write <code>mycontextmanager.__exit__(None, None, None)</code>, but that seems awkward. Also, it is also entirely possible that I'd forget to close the context manager, which is not a big deal for files, but may be more problematic for e.g. an internet session.</p>
  <p>I could also use <a href="https://docs.python.org/3/library/weakref.html#comparing-finalizers-with-del-methods" rel="nofollow noreferrer">finalizers</a> to make sure that things are closed, but relying on the garbage collector for anything other than memory leaks seems a shaky way to do things, so I feel that finalizers should be a supplemental solution at best.</p>
  <p>So is there a more elegant solution to the problem of using context managers in an interactive shell? Should my own context manager classes always provide something like a <code>close()</code> method as a good practice?</p>