I came across the Python with statement for the first time today. I’ve been using Python lightly for several months and didn’t even know of its existence! Given its somewhat obscure status, I thought it would be worth asking:
- What is the Python
withstatement
designed to be used for? - What do
you use it for? - Are there any
gotchas I need to be aware of, or
common anti-patterns associated with
its use? Any cases where it is better usetry..finallythanwith? - Why isn’t it used more widely?
- Which standard library classes are compatible with it?
I believe this has already been answered by other users before me, so I only add it for the sake of completeness: the
withstatement simplifies exception handling by encapsulating common preparation and cleanup tasks in so-called context managers. More details can be found in PEP 343. For instance, theopenstatement is a context manager in itself, which lets you open a file, keep it open as long as the execution is in the context of thewithstatement where you used it, and close it as soon as you leave the context, no matter whether you have left it because of an exception or during regular control flow. Thewithstatement can thus be used in ways similar to the RAII pattern in C++: some resource is acquired by thewithstatement and released when you leave thewithcontext.Some examples are: opening files using
with open(filename) as fp:, acquiring locks usingwith lock:(wherelockis an instance ofthreading.Lock). You can also construct your own context managers using thecontextmanagerdecorator fromcontextlib. For instance, I often use this when I have to change the current directory temporarily and then return to where I was:Here’s another example that temporarily redirects
sys.stdin,sys.stdoutandsys.stderrto some other file handle and restores them later:And finally, another example that creates a temporary folder and cleans it up when leaving the context: