Defining the __enter__() and __exit__() methods
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 transient global changes. This might be a change to the database transaction status or a change to the locking status, 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
class KnownSequence:
def __init__(self, seed=0):
self.seed= 0
def __enter__(self):
self.was= random.getstate()
random.seed(self.seed, version=1)
return self
def __exit__...