Skip to content
Advertisement

Execute code line by line interactively in console inside `with` block

When testing things interactively in a console, sometimes I use with statements. However, because they increase indentation, the prompt changes from >>> to ... and the execution stops until I return to the lowest indentation. It makes sense for function definitions, because the code isn’t actually executed inside the function definition. But then there are loops (first iteration could be executed before the loop is fully described), conditional statements, try, with

Is there a way to enable such execution? Or do I have to manually operate on the context manager’s interface like so:

>>> cm = open("E:/test.txt")
>>> f = cm.__enter__()
>>> f.read()
'contents of the file'
>>> cm.__exit__()

Advertisement

Answer

It doesn’t really make sense for the console to execute lines one-by-one inside a with statement. Many context managers take care to suppress certain kinds of exceptions that take place inside the with block, and many others take care to perform some kind of cleanup action before raising certain kinds of exceptions. open is a really good example of this — if there’s some kind of exception that occurs while python is reading the file, using open as a context manager will ensure that the file is closed again before python raises the exception.


This code:

with open("E:/test.txt", "r") as f:
    var = f.read()

is identical in what it achieves to this code:

try:
    f = open("E:/test.txt", "r")
    var = f.read()
finally:
    f.close()

If you’re executing code in the interactive console, it would probably be better to use the “old-fashioned” pre-context-manager way of opening and reading files, but without the exception-handling.


Good python practice outside of the interactive console:

with open("E:/test.txt", "r") as f:
    var = f.read()  # file is automatically closed as the `with` block ends

“Old-fashioned” solution for executing code line-by-line in the interactive console (dangerous in an actual script — no exception handling!):

>>> f = open("E:/test.txt", "r")
>>> var = f.read()
>>> f.close()  # Remember to manually close the file, since we're not using a `with` statement!
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement