Tuesday, 26 November 2013

Context managers in python --verbose

Context manager is a piece of code that wraps around another block of code, creating a local run time context for that block. A context type is an object with two methods .__entry__() and .__exit__(exc_type, exc_val, exc_tb). Basically these two methods define the setup and tear down of the state. This state is insulated from outer scopes and context managers are used to execute code inside this 'sandbox' environment to prevent any changes to outer namespaces. Context managers are also useful when refactoring code. If you have code that follows a similar pattern where you need to preform some form of setup and tear down each time, then you can abstract that into a context manager.
Context manager types are often used with the 'with' statement to wrap code. The with statement executes .__exit__() callable of the context type and assigns the return value to the 'as' target (if any). When the wrapped code finishes execution, the .__exit__(exc_type, exc_value, exc_tb) is called. This code performs clean up and handles any exceptions that were raised. To be more precise, the return type of this callable is a boolean, true to signal that all exceptions raised will be suppressed (either during the exec
ution of the block statement or the execution of the __exit__()) or False to indicate that exceptions should propagate further.

No comments:

Post a Comment