Using the ‘with’ statement for custom python objects to manage resources.

If you’ve used python for a while you are familiar with the with statement, especially for reading and writing files. Using the with statement guarantees that the file will be closed even if an error occurs while executing the block of code inside the with statement

This is kind of similar to using try... except... finally construct, except it's more cleaner and provides a more powerful abstraction.

In Python, this is achieved through a context manager.

What is a Context Manager?

From the Python documentation:

A context manager is an object that defines the runtime context to be established when executing a with statement. The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code. Context managers are normally invoked using the with statement (described in section The with statement), but can also be used by directly invoking their methods.
Typical uses of context managers include saving and restoring various kinds of global state, locking and unlocking resources, closing opened files, etc. …



Software Engineer Python, Elixir/Erlang, NLP https://baduboahen.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store