Context Managers and the 'with' keyword in Python3

Context Managers in python3 are a simple but powerful feature.

The most common example of a context-manager in action is opening a file and not having to worry about manually closing it later on, and instead letting the context manager implementation (in this case the open function) do the work for you:

1with open("file", "rb") as file:
2    ...

Instead of having to manually call file.close() later on, once the “with” block ends, the appropriate cleanup actions (in this case flushing the file to disk and closing the file descriptors) are automatically performed.

This is all accomplished using 2 underlying methods defined in the context manager (in the above case the object returned by the open() call):

  • __enter__
    • this method is called right before the block of code underneath the with statement is entered
    • its return value is the one passed to us in form of the variable declared after the as keyword
    • once it finishes executing the block of code underneath the with statement is executed
  • __exit__
    • this method is called after the with block of code finishes executed
    • it gets passed 3 additional arguments that contain information about the first exception that occurred inside of the with code block (if no exception occurred they are all None):
      • exception_type: the class of the exception
      • exception_value: its associated value
      • exception_traceback: traceback information in form of the traceback class (types.TracebackType in the types module)

In order to implement context manager support in your functions, just make sure that they expose the above two methods, and they will be context-manager compliant.