The defining feature of a context manager is that it has two special methods: __enter__() and __exit__(). These are used by the with statement to enter and exit the context. We'll use a simple context so that we can see how they work.
We'll often use context managers to make global state changes. This might be a change to the database transaction status or a change to the locking status of a resource, something that we want to do and then undo when the transaction is complete.
For this example, we'll make a global change to the random number generator. We'll create a context in which the random number generator uses a fixed and known seed, providing a fixed sequence of values.
The following is the context manager class definition:
import random
from typing import Optional, Type
from types import TracebackType
class...