Python with statement and context managers

Introduction

Welcome to a new code snippets post. Today, we are going to summarize the use of with statement and context managers in Python. In coding, a typical scenario is to acquire a resource, use it and finally release the resource. If an exception occurs, the program may not have a chance to free the allocated resource (i.e. a leak). In most programming languages, the solution is to use a try catch clause. In Python, we can use the same technique (i.e. try catch clause) however, using with statement is a better alternative. It eliminates extra lines of code and makes sure the resource is freed automatically even in the case of exceptions. So, how does Python implement that? The answer is context managers…

Context managers

Behind the scenes, Python with statement uses a context manager. The keyword context refers to a resource (ex. file, socket, etc) context. Context manager is simply a class that implements the context manager protocol or a function that returns a context manager object. To implement the context manager protocol, define a class which implements the enter and exit methods such that…

  • Implement __enter__ method. This method should return the resource that we are tying to acquire
  • Implement __exit__ method. This method should release the acquired resource

We will demonstrate how to implement our own context manager later. Let us now describe the with statement syntax…

With statement syntax

The with statement syntax can be described as follows…

  • The keyword with at the beginning followed by
  • class or function that returns a context manager object followed by
  • The keyword as followed by
  • An alias for the returned resource followed by
  • The with statement body inside which we do something with the resource
  • The moment the body is out of scope, the cleanup part is executed automatically

Here is how the with statement syntax looks like…

For example, writing to a file…

Which is equivalent to…

Context manager example

In this example, we are going to implement a dummy context manger and use the with statement. Take a look…

If you run the code snippet above, you should get the following output…

Sounds like a good idea! Let us mention few candidate scenarios to use the with statement…

When to use with statement?

Any pair of operations that can be done together such as preparation & cleanup, setup & teardown, etc. are good candidates for using a with statement. A typical example is opening a file, writing to then closing the file. There are countless other examples that are good fit for the with statement. To mention a few…

  • Reading from and writing to files
  • Networking and sockets
  • Database access
  • Locks in multithreaded applications

with statement example

The typical example of opening a file was demonstrated earlier, let us take one more example…

Database connection

Database connection is a good example on using context managers and with statement as it involves a setup stage (i.e. connection) and clean stage (i.e. commit and close). Take a look…

If you run the code snippet above, you should get the following output…

Decorator based context manager

Context managers can also be implemented using decorators. For more information about decorators, refer to the references section. The @contextmanager decorator defined in the contextlib library can be used to decorate a generator function (refer to the references section for more information about generators) that calls yield exactly once. Everything before the yield statement is considered the code for enter. Everything after the yield statement is the code for exit. Here is an example on opening a file…

Nesting context managers

Context managers can be composed. Take a look at the following example…

If you run the code snippet above, you should get the following output…

You can also use the following syntax…

and this…

That is it for today, let us summarize…

Summary

  • Python with statement can be used to acquire a resource, consume it and finally release the resource while eliminating extra lines of code and making sure the resource is freed automatically even in the case of exceptions
  • Python implements the with statement using a context manager. Context manager is simply a class that implements the context manager protocol or a function that returns a context manager object
  • The context manager protocol has an enter and exit method where setup and tear down operations take place
  • The syntax for the with statement in Python is as follows
  • Any pair of operations that can be done together such as preparation & cleanup, setup & teardown, etc. are good candidates for using a with statement. The typical example is opening a file, writing to then closing the file
  • The with statement in Python can be implemented using either a class or a decorator
  • The with statement in Python can be nested as well

References

Thanks for reading. Please comeback…

Tags:

Add a Comment

Your email address will not be published. Required fields are marked *