03: Python context manager tutorial

Q. What is a Python context manager?
A. The most common use of context managers is to properly manage resources. Context managers are a way of allocating and releasing some sort of resource exactly where you need it. The simplest example is file access:

Instead of:

The following code ensures that the file handle is closed, but very verbose.

The 11 is the number of bytes written.

Use context manager:

Another example would be in acquiring & releasing thread locks:

Instead of:
Use context manager:

Very concise code that acquires & releases the lock.

Q. How do you go about implementing your own context manager?
A. A way to make a context manager is to make a class which follows the context management protocol, by implementing __enter__ and __exit__ methods.

Create a Python file named “my_file.py“.

Type the following code

The __init__() method sets up the file name to open and the mode to open it in. The __enter__() opens and returns the file and the reference ti it so that you can refer to it in __exit__(). The __exit__() just closes the file.

Now, we can use the “MyFile” context manager.

The simplest way is using the @contextmanager decorator from the contextlib library, and invoking yield in your context manager function between the setup and teardown steps.

contextlib ContextDecorator


Type the following content:

Now, on the Python REPL:

You can see both the decorator pattern & context manager in action.

pytest example

300+ Java Interview FAQs

800+ Java Interview Q&As