I saw this question, and I understand when you would want to use with foo() as bar:
, but I don't understand when you would just want to do:
bar = foo()
with bar:
....
Doesn't that just remove the tear-down benefits of using with ... as
, or am I misunderstanding what is happening? Why would someone want to use just with
?
The advantage of using a with statement is that it is guaranteed to close the file no matter how the nested block exits. If an exception occurs before the end of the block, it will close the file before the exception is caught by an outer exception handler.
with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner. file .
4 Answers. Show activity on this post. Using with means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need.
To expand a bit on @freakish's answer, with
guarantees entry into and then exit from a "context". What the heck is a context? Well, it's "whatever the thing you're with-ing makes it". Some obvious ones are:
Less obvious ones might even include certain kinds of exception trapping: you might catch divide by zero, do some arithmetic, and then stop catching it. Of course that's built into the Python syntax: try
... except
as a block! And, in fact, with
is simply a special case of Python's try/except/finally mechanisms (technically, try/finally
wrapped around another try
block; see comments).
The as
part of a with
block is useful when the context-entry provides some value(s) that you want to use inside the block. In the case of the file or database record, it's obvious that you need the newly-opened stream, or the just-obtained record. In the case of catching an exception, or holding a lock on a data structure, there may be no need to obtain a value from the context-entry.
For example when you want to use Lock()
:
from threading import Lock
myLock = Lock()
with myLock:
...
You don't really need the Lock()
object. You just need to know that it is on.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With