Context managers and with syntax

class Transaction:
    def __enter__(self):
        print("Beginning transaction")
        # Do everything needed before doing the transaction - connect to databases, open files, etc.
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        # Do everything needed after finishing it - disconnect, close files, etc.
        print("Finished transaction")

# Using the context manager
with Transaction():
    print("Performing transaction operations")
Beginning transaction
Performing transaction operations
Finished transaction
import time

class Timer:
    def __enter__(self):
        self.start_time = time.time()
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        self.end_time = time.time()
        elapsed_time = self.end_time - self.start_time
        print(f"Time taken: {elapsed_time:.2f} seconds")

# Using the context manager
with Timer():
    # Do some time-consuming operation, for example:
    time.sleep(2)

File objects in Python ARE context managers

  • You can easily deal with opening and closing a file in Python using its context manager functions, which are part of the file object.
with open('example.txt', 'w') as f:  # returns a file object with "open", which will be referred to as "f"
    f.write('Hello, world!')