Search code examples
pythonpython-3.xipython

Python interactive REPL inside a with statement


From an python interactive session, is there a way to enter a REPL loop inside a with statement?

Normally, a with statement is executed as a single block

>>>
>>> with app.app_context():
>>> ...   # Normally this is executed as a single block, all at once

I'd like to be able to run code in an interactive session, in the context.

>>>
>>> with app.app_context():
>>> # do stuff here in a REPL loop

Solution

  • You can't exactly mimic a with statement, but you can probably get close by calling app.app_context().__enter__() manually.

    This won't __exit__ automatically if there's an exception, but otherwise it should work the same (you might need to call __exit__ yourself when you're done, I'm not sure what exactly that context manager does).