context manager python code example

Example 1: python context manager example

class File:
  def __init__(self, filename, method):
    self.file = open(filename, method)
   
  def __enter__(self):
    print("Enter")
    return self.file
  
  def __exit__(self, type, value, traceback):
    print(f"{type}, {value}, {traceback}")
    print("Exit")
    self.file.close()

with File("file.txt", "w") as f:
  print("Middle")
  f.write("hello")
  raise Exception()
  raise FileExistsEoor()

Example 2: python contextmanager

Context manager with samples:
https://book.pythontips.com/en/latest/context_managers.html

Tags:

Misc Example