With Keyword
Updated on 28 Dec 2022
Introduction
The with
keyword can be used for dealing with unmanaged resources. Let’s consider the following scenario.
- Open file
- Do something
- Close file
We are most likely going to wrap this code in a try - finally
block to ensure that the call to Close the file is actually done, even if something happens (exception) during the Do something phase.
We might have code that looks like this:
try:
f = open('data/dummyData1.txt')
lines = f.read()
print(lines)
finally:
f.close()
Using with
Using the with
keyword we can now use code like this instead:
with open("data/dummyData1.txt") as f:
lines = f.read()
print(lines)
We don’t have to worry about closing the file because that has already been done as part of the with
keyword.
Internals of with
Python’s with statement supports the concept of a runtime context defined by a context manager.
An explanation of the history of with
can be found here, and below is a basic summary using code.
class controlled_execution:
def __enter__(self):
set things up
return thing
def __exit__(self, type, value, traceback):
tear things down
with controlled_execution() as thing:
some code
When the with
statement is executed, Python evaluates the expression, calls the enter method on the resulting value (which is called a “context guard”), and assigns whatever enter returns to the variable given by as
. Python will then execute the code body, and no matter what happens in that code, call the guard object’s exit method.
Building your class with a context manager
Naturally you can build your own classes to behave the same.